Skip to content

Commit 920c9a9

Browse files
committed
valid palindrome
1 parent 920d92b commit 920c9a9

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed

valid-palindrome/JisooPyo.kt

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package leetcode_study
2+
3+
import io.kotest.matchers.shouldBe
4+
import org.junit.jupiter.api.Test
5+
6+
/**
7+
* Leetcode
8+
* 125. Valid Palindrome
9+
* Easy
10+
*/
11+
class ValidPalindrome {
12+
/**
13+
* Runtime: 4 ms(Beats: 98.27 %)
14+
* Time Complexity: O(n)
15+
*
16+
* Memory: 38.22 MB(Beats: 46.74 %)
17+
* Space Complexity: O(1)
18+
*/
19+
fun isPalindrome(s: String): Boolean {
20+
var left = 0
21+
var right = s.length - 1
22+
while (left <= right) {
23+
when (s[left]) {
24+
// 왼쪽의 문자가 alphanumeric일 때
25+
in 'a'..'z', in 'A'..'Z', in '0'..'9' -> {
26+
27+
when (s[right]) {
28+
// 오른쪽의 문자가 alphanumeric일 때
29+
in 'a'..'z', in 'A'..'Z', in '0'..'9' -> {
30+
// 문자 비교
31+
if (s[left].equals(s[right], true)) {
32+
left++
33+
right--
34+
continue
35+
} else {
36+
return false
37+
}
38+
}
39+
// 오른쪽의 문자가 alphanumeric이 아닐 때
40+
else -> {
41+
right--
42+
continue
43+
}
44+
}
45+
}
46+
47+
// 왼쪽의 문자가 alphanumeric이 아닐 때
48+
else -> {
49+
left++
50+
continue
51+
}
52+
}
53+
}
54+
return true
55+
}
56+
57+
/**
58+
* 개선한 버전
59+
* Runtime: 5 ms(Beats: 87.14 %)
60+
* Time Complexity: O(n)
61+
*
62+
* Memory: 37.76 MB(Beats: 61.52 %)
63+
* Space Complexity: O(1)
64+
*/
65+
fun isPalindrome2(s: String): Boolean {
66+
var left = 0
67+
var right = s.length - 1
68+
69+
while (left < right) {
70+
// 왼쪽에서 유효한 문자를 찾음
71+
while (left < right && !s[left].isLetterOrDigit()) {
72+
left++
73+
}
74+
75+
// 오른쪽에서 유효한 문자를 찾음
76+
while (left < right && !s[right].isLetterOrDigit()) {
77+
right--
78+
}
79+
80+
// 문자 비교
81+
if (!s[left].equals(s[right], ignoreCase = true)) {
82+
return false
83+
}
84+
85+
left++
86+
right--
87+
}
88+
return true
89+
}
90+
91+
@Test
92+
fun test() {
93+
isPalindrome("A man, a plan, a canal: Panama") shouldBe true
94+
isPalindrome("race a car") shouldBe false
95+
isPalindrome(" ") shouldBe true
96+
97+
isPalindrome2("A man, a plan, a canal: Panama") shouldBe true
98+
isPalindrome2("race a car") shouldBe false
99+
isPalindrome2(" ") shouldBe true
100+
}
101+
}

0 commit comments

Comments
 (0)