-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse-only-letters.rs
51 lines (46 loc) · 1.31 KB
/
reverse-only-letters.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
struct Solution;
impl Solution {
pub fn reverse_only_letters(s: String) -> String {
if s.len() == 1 {
return s;
}
let mut left = 0;
let mut right = s.len() - 1;
let mut s = s.chars().collect::<Vec<char>>();
let letter = |c| ('a'..='z').any(|x| x == c) || ('A'..='Z').any(|x| x == c);
while left <= right {
if !letter(s[left]) {
left += 1;
continue;
}
if !letter(s[right]) {
right -= 1;
continue;
}
s.swap(left, right);
left += 1;
right -= 1;
}
s.into_iter().collect::<String>()
}
}
fn main() {
println!("{}", Solution::reverse_only_letters("ab-cd".to_string()));
}
#[cfg(test)]
mod tests {
use crate::Solution;
#[test]
fn test_impl1() {
assert_eq!(Solution::reverse_only_letters("a".to_string()), "a");
assert_eq!(Solution::reverse_only_letters("ab-cd".to_string()), "dc-ba");
assert_eq!(
Solution::reverse_only_letters("a-bC-dEf-ghIj".to_string()),
"j-Ih-gfE-dCba"
);
assert_eq!(
Solution::reverse_only_letters("Test1ng-Leet=code-Q!".to_string()),
"Qedo1ct-eeLg=ntse-T!"
);
}
}