File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // naive한 풀이
2+ // tc: O(n)
3+ // sc: O(n)
4+ const isPalindromeNaive = function ( s ) {
5+ const str = s . toLowerCase ( ) . replace ( / [ ^ a - z 0 - 9 ] / g, '' ) ; // 이 부분에서 공간복잡도가 O(n)
6+ let leftIdx = 0 ;
7+ let rightIdx = str . length - 1 ;
8+
9+ while ( leftIdx <= rightIdx ) {
10+ if ( str [ leftIdx ] !== str [ rightIdx ] ) {
11+ return false ;
12+ } else {
13+ leftIdx ++ ;
14+ rightIdx -- ;
15+ }
16+ }
17+ return true ;
18+ } ;
19+
20+ // 좀 더 최적화 된 풀이
21+ // tc: O(n)
22+ // cs: O(1)
23+ const isPalindrome = function ( s ) {
24+ let leftIdx = 0 ;
25+ let rightIdx = s . length - 1 ;
26+
27+ while ( leftIdx < rightIdx ) {
28+ while ( leftIdx < rightIdx && ! isAlphaNumeric ( s [ leftIdx ] ) ) leftIdx ++ ;
29+ while ( leftIdx < rightIdx && ! isAlphaNumeric ( s [ rightIdx ] ) ) rightIdx -- ;
30+
31+ if ( s [ leftIdx ] . toLowerCase ( ) !== s [ rightIdx ] . toLowerCase ( ) ) return false ;
32+
33+ leftIdx ++ ;
34+ rightIdx -- ;
35+ }
36+ return true ;
37+ } ;
38+
39+ function isAlphaNumeric ( char ) {
40+ return / [ a - z A - Z 0 - 9 ] / . test ( char ) ;
41+ }
You can’t perform that action at this time.
0 commit comments