File tree Expand file tree Collapse file tree 1 file changed +82
-0
lines changed Expand file tree Collapse file tree 1 file changed +82
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 2차
2
+ // TC: O(N)
3
+ // SC: O(N)
4
+ // N: s.length
5
+
6
+ /**
7
+ * @param {string } s
8
+ * @return {boolean }
9
+ */
10
+ var isPalindrome = function ( s ) {
11
+ const phrase = s . toLowerCase ( ) ;
12
+ // 1. 투포인터를 양끝에서 시작합니다.
13
+ let left = 0 ;
14
+ let right = phrase . length - 1 ;
15
+
16
+ while ( left < right ) {
17
+ // 2. 현재 가리키는 문자가 영소문자, 숫자가 아니면 건너뜁니다.
18
+ while ( left < right && ! isValid ( phrase [ left ] ) ) {
19
+ left += 1 ;
20
+ }
21
+ while ( left < right && ! isValid ( phrase [ right ] ) ) {
22
+ right -= 1 ;
23
+ }
24
+
25
+ // 3. 문자의 갯수가 홀수인 경우 투 포인터가 모두 가운데를 가리키는 경우 순회를 끝났다고 생각합니다.
26
+ if ( left === right ) {
27
+ break ;
28
+ }
29
+
30
+ // 4. 투 포인터가 가리키는 문자가 다른 경우 정답(false)를 반환합니다.
31
+ if ( phrase [ left ] !== phrase [ right ] ) {
32
+ return false ;
33
+ }
34
+
35
+ // 5. 다음 문자로 넘어갑니다.
36
+ left += 1 ;
37
+ right -= 1 ;
38
+ }
39
+
40
+ // 6. 모든 순회가 끝냈다면 palindrome이라고 판단합니다.
41
+ return true ;
42
+
43
+ function isValid ( spell ) {
44
+ if ( "0" <= spell && spell <= "9" ) {
45
+ return true ;
46
+ }
47
+ if ( "a" <= spell && spell <= "z" ) {
48
+ return true ;
49
+ }
50
+
51
+ return false ;
52
+ }
53
+ } ;
54
+
55
+ // 1차
56
+ // TC: O(N)
57
+ // SC: O(N)
58
+ // N: s.length
59
+
60
+ /**
61
+ * @param {string } s
62
+ * @return {boolean }
63
+ */
64
+ var isPalindrome = function ( s ) {
65
+ // 1. 문자열을 모두 소문자로 바꾸고 영소문자, 숫자만 남기고 모두 제거합니다.
66
+ const phrase = s
67
+ . toLowerCase ( )
68
+ . split ( "" )
69
+ . filter (
70
+ ( spell ) =>
71
+ ( "0" <= spell && spell <= "9" ) || ( "a" <= spell && spell <= "z" )
72
+ ) ;
73
+
74
+ // 2. 양끝의 문자를 확인해서 palindrome인지 판별합니다.
75
+ for ( let index = 0 ; index < Math . floor ( phrase . length / 2 ) ; index ++ ) {
76
+ if ( phrase [ index ] !== phrase [ phrase . length - index - 1 ] ) {
77
+ return false ;
78
+ }
79
+ }
80
+
81
+ return true ;
82
+ } ;
You can’t perform that action at this time.
0 commit comments