Skip to content

Commit 7b9c6fb

Browse files
committed
feat: 125. Valid Palindrome
1 parent e1173dd commit 7b9c6fb

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

contains-duplicate/HC-kang.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
/**
2+
* https://leetcode.com/problems/contains-duplicate
3+
* T.C. O(n)
4+
* S.C. O(n)
5+
*/
16
impl Solution {
27
pub fn contains_duplicate(nums: Vec<i32>) -> bool {
38
use std::collections::HashSet;

valid-palindrome/HC-kang.rs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* https://leetcode.com/problems/valid-palindrome
3+
* T.C. O(n)
4+
* S.C. O(n)
5+
*/
6+
impl Solution {
7+
pub fn is_palindrome(s: String) -> bool {
8+
let s: Vec<char> = s
9+
.chars()
10+
.filter(|c| c.is_alphanumeric())
11+
.map(|c| c.to_ascii_lowercase())
12+
.collect(); // T.C. O(n), S.C. O(n)
13+
14+
let mut i = 0;
15+
let mut j = s.len().saturating_sub(1);
16+
17+
// T.C. O(n)
18+
while i < j {
19+
if s[i] != s[j] {
20+
return false;
21+
}
22+
i += 1;
23+
j -= 1;
24+
}
25+
true
26+
}
27+
}
28+
29+
/**
30+
* 최적화
31+
* T.C. O(n)
32+
* S.C. O(1)
33+
*/
34+
impl Solution {
35+
pub fn is_palindrome(s: String) -> bool {
36+
let s = s.as_bytes();
37+
let (mut left, mut right) = (0, s.len().saturating_sub(1));
38+
39+
while (left < right) {
40+
while (left < right && !Self::is_alphanumeric(s[left])) {
41+
left += 1;
42+
}
43+
44+
while (left < right && !Self::is_alphanumeric(s[right])) {
45+
right -= 1;
46+
}
47+
48+
if left < right {
49+
if s[left].to_ascii_lowercase() != s[right].to_ascii_lowercase() {
50+
return false;
51+
}
52+
left += 1;
53+
right -= 1;
54+
}
55+
}
56+
57+
true
58+
}
59+
60+
fn is_alphanumeric(c: u8) -> bool {
61+
(c >= b'a' && c <= b'z') ||
62+
(c >= b'A' && c <= b'Z') ||
63+
(c >= b'0' && c <= b'9')
64+
}
65+
}

0 commit comments

Comments
 (0)