-
Notifications
You must be signed in to change notification settings - Fork 0
/
valid_palindrome.rs
74 lines (64 loc) · 1.89 KB
/
valid_palindrome.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/// A phrase is a palindrome if, after converting all uppercase letters into
/// lowercase letters and removing all non-alphanumeric characters, it reads
/// the same forward and backward. Alphanumeric characters include letters and
/// numbers.
///
/// Given a string `s`, return `true` if it is a palindrome, or `false`
/// otherwise.
struct Solution;
impl Solution {
pub fn is_palindrome(s: String) -> bool {
let mut result = true;
let chars: Vec<char> = s.chars().collect();
let mut left = 0;
let mut right = s.len() - 1;
while left < right {
let mut left_char = chars[left];
let mut right_char = chars[right];
if !left_char.is_ascii_alphanumeric() {
left += 1;
} else if !right_char.is_ascii_alphanumeric() {
right -= 1;
} else {
left_char = left_char.to_ascii_lowercase();
right_char = right_char.to_ascii_lowercase();
if left_char != right_char {
result = false;
break;
} else {
left += 1;
right -= 1;
}
}
}
result
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn example_1() {
let s = "A man, a plan, a canal: Panama".to_string();
let result = Solution::is_palindrome(s);
assert!(result);
}
#[test]
fn example_2() {
let s = "race a car".to_string();
let result = Solution::is_palindrome(s);
assert!(!result);
}
#[test]
fn example_3() {
let s = " ".to_string();
let result = Solution::is_palindrome(s);
assert!(result);
}
#[test]
fn numbers() {
let s = "0P".to_string();
let result = Solution::is_palindrome(s);
assert!(!result);
}
}