File tree 2 files changed +70
-0
lines changed
2 files changed +70
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/contains-duplicate
3
+ * T.C. O(n)
4
+ * S.C. O(n)
5
+ */
1
6
impl Solution {
2
7
pub fn contains_duplicate ( nums : Vec < i32 > ) -> bool {
3
8
use std:: collections:: HashSet ;
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments