345. Reverse Vowels of a String
Description of Problem
Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.
Example 1:
Input: s = "hello"
Output: "holle"
Example 2:
Input: s = "leetcode"
Output: "leotcede"
Constraints:
1 <= s.length <= 3 * 10^5sconsist of printable ASCII characters.
Solution
Code (Rust)
impl Solution {
pub fn reverse_vowels(s: String) -> String {
let mut s = s;
let mut bytes = unsafe { s.as_bytes_mut() };
let (mut i, mut j) = (0, bytes.len() - 1);
while (i < j){
match (bytes[i], bytes[j]) {
(65|69|73|79|85|97|101|105|111|117, 65|69|73|79|85|97|101|105|111|117) => {
let temp = bytes[i];
bytes[i] = bytes[j];
bytes[j] = temp;
i+=1; j-=1;
},
(65|69|73|79|85|97|101|105|111|117, _) => {
j-=1;
},
(_, 65|69|73|79|85|97|101|105|111|117) => {
i+=1;
},
(_,_) => { i+=1; j-=1; }
}
}
return s;
}
}
Complexity
- n is length of string
Time Complexity
- \(T(n)=O(n)\)
Auxiliary Space
- \(S(n)=O(1)\)