#917
Easy Algorithms Reverse only letters
Two Pointers String
68.2% acceptance
Feb 25, 2026
2438
86
Given a string s, reverse the string according to the following rules:
All the characters that are not English letters remain in the same position.
All the English letters (lowercase or uppercase) should be reversed.
Return s after reversing it.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn reverse_only_letters(s: String) -> String {
let mut chars: Vec<char> = s.chars().collect();
let (mut l, mut r) = (0, chars.len() - 1);
while l < r {
while l < r && !chars[l].is_alphabetic() { l += 1; }
while l < r && !chars[r].is_alphabetic() { if r == 0 { break; } r -= 1; }
if l < r { chars.swap(l, r); l += 1; if r > 0 { r -= 1; } }
}
chars.iter().collect()
}
}