Skip to content

Commit f273007

Browse files
author
jinvicky
committed
valid palindrome solution
1 parent b88df03 commit f273007

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

valid-palindrome/jinvicky.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Solution {
2+
3+
/**
4+
* 런타임 231ms
5+
* [생각]
6+
* for문으로 알파벳, 숫자를 제외한 특수문자들을 제거한 후에 투 포인터 알고리즘으로 풀이하자.
7+
*/
8+
public boolean isPalindrome(String s) {
9+
StringBuilder sb = new StringBuilder();
10+
for (char c : s.toCharArray()) {
11+
if (Character.isDigit(c)) {
12+
sb.append(c);
13+
}
14+
if (Character.isAlphabetic(c)) {
15+
sb.append(Character.toLowerCase(c));
16+
}
17+
}
18+
19+
int left = 0;
20+
int right = sb.toString().length() - 1;
21+
22+
while (left <= right) {
23+
if (sb.toString().charAt(left) != sb.toString().charAt(right)) {
24+
return false;
25+
}
26+
left++;
27+
right--;
28+
}
29+
return true;
30+
}
31+
32+
/**
33+
* 런타임 7ms
34+
* [생각]
35+
* 굳이 투 포인터로? 이미 활용중인 StringBuilder를 reverse()본과 원본을 비교하면 탐색 필요없다.
36+
* 또한 " " 케이스는 사전에 리턴처리한다.
37+
*/
38+
public boolean isPalindrome2(String s) {
39+
if (s.equals(" "))
40+
return true;
41+
42+
StringBuilder sb = new StringBuilder();
43+
for (char c : s.toCharArray()) {
44+
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || Character.isDigit(c)) {
45+
sb.append(Character.toLowerCase(c));
46+
}
47+
}
48+
return sb.toString().equals(sb.reverse().toString());
49+
}
50+
}

0 commit comments

Comments
 (0)