File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Constraints
3
+ * - 1 <= s.length <= 2 * 10^5
4
+ * - s consists only of printable ASCII characters.
5
+ *
6
+ * Output
7
+ * - true : 좌우 동일
8
+ * - false : 좌우 비동일
9
+ */
10
+
11
+
12
+ class Solution {
13
+ public boolean isPalindrome (String s ) {
14
+
15
+ // 해결법 1 (투포인터)
16
+ // 시간복잡도: O(N), 공간 복잡도 : O(1)
17
+ // 2ms & Beats 99.05%
18
+ int left = 0 , right = s .length () - 1 ;
19
+
20
+ while (left < right ) {
21
+ // (1)
22
+ if (!Character .isLetterOrDigit (s .charAt (left ))) {
23
+ left ++;
24
+ }
25
+ else if (!Character .isLetterOrDigit (s .charAt (right ))) {
26
+ right --;
27
+ }
28
+ else {
29
+ if (Character .toLowerCase (s .charAt (left )) != Character .toLowerCase (s .charAt (right ))) {
30
+ return false ;
31
+ }
32
+
33
+ left ++;
34
+ right --;
35
+ }
36
+
37
+
38
+ // (2)
39
+ while (left < right && !Character .isLetterOrDigit (s .charAt (left ))) {
40
+ left ++;
41
+ }
42
+ while (left < right && !Character .isLetterOrDigit (s .charAt (right ))) {
43
+ right --;
44
+ }
45
+ if (Character .toLowerCase (s .charAt (left )) != Character .toLowerCase (s .charAt (right ))) {
46
+ return false ;
47
+ }
48
+ left ++;
49
+ right --;
50
+ }
51
+
52
+ return true ;
53
+
54
+ // 해결법 2 (Stream API)
55
+ // 시간 복잡도 : O(N), 공간 복잡도 : O(N)
56
+ // 133ms & Beats 5.58%
57
+ String filtered = s .chars ()
58
+ .filter (Character ::isLetterOrDigit )
59
+ .mapToObj (c -> String .valueOf ((char ) Character .toLowerCase (c )))
60
+ .reduce ("" , String ::concat );
61
+
62
+ return IntStream .range (0 , filtered .length () / 2 )
63
+ .allMatch (i -> filtered .charAt (i ) == filtered .charAt (filtered .length () - 1 - i ));
64
+ }
65
+ }
You can’t perform that action at this time.
0 commit comments