rustgym/leetcode/
_345_reverse_vowels_of_a_string.rs1struct Solution;
2
3impl Solution {
4 fn is_vowel(c: char) -> bool {
5 matches!(c, 'a' | 'e' | 'i' | 'o' | 'u' | 'A' | 'E' | 'I' | 'O' | 'U')
6 }
7
8 fn reverse_vowels(s: String) -> String {
9 let mut a: Vec<char> = s.chars().collect();
10 let n = a.len();
11 if n == 0 {
12 return "".to_string();
13 }
14 let mut l = 0;
15 let mut r = n - 1;
16 while l < r {
17 if Self::is_vowel(a[l]) && Self::is_vowel(a[r]) {
18 a.swap(l, r);
19 l += 1;
20 r -= 1;
21 } else {
22 if !Self::is_vowel(a[l]) {
23 l += 1;
24 }
25 if !Self::is_vowel(a[r]) {
26 r -= 1;
27 }
28 }
29 }
30 a.iter().collect()
31 }
32}
33
34#[test]
35fn test() {
36 let s = "hello".to_string();
37 let t = "holle".to_string();
38 assert_eq!(Solution::reverse_vowels(s), t);
39 let s = "leetcode".to_string();
40 let t = "leotcede".to_string();
41 assert_eq!(Solution::reverse_vowels(s), t);
42 let s = "a.".to_string();
43 let t = "a.".to_string();
44 assert_eq!(Solution::reverse_vowels(s), t);
45}