Skip to content

Commit 226ca63

Browse files
committed
valid-palindrome solution
1 parent bbc7cba commit 226ca63

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public boolean isPalindrome(String s) {
3+
/**
4+
1. ๋ฌธ์ œ: ํŒฐ๋ฆฐ๋“œ๋กฌ์ธ์ง€ ํŒ๋‹จํ•˜๋Š” ๋ฌธ์ œ.
5+
2. ์กฐ๊ฑด: ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ ๋ณ€ํ™˜, ๋ฌธ์ž ๋˜๋Š” ์ˆซ์ž๊ฐ€ ์•„๋‹Œ๊ฑด ๋ชจ๋‘ ์ œ๊ฑฐ (๊ณต๋ฐฑ, ์‰ผํ‘œ ๋“ฑ))
6+
- left, right index ์ด์ค‘ ํฌ์ธํ„ฐ๋กœ ํ’€์ด
7+
time complexity : O(n)
8+
space complexity : O(1)
9+
*/
10+
boolean answer = true;
11+
//๋ฌธ์ž์—ด ์ถ”๊ฐ€ํ•˜๋ฉด space complexity : O(n)
12+
//s = s.toLowerCase();
13+
//s = s.replaceAll("[^0-9a-z]", "");
14+
int left = 0 ;
15+
int right = s.length() - 1;
16+
17+
while(left < right) {
18+
char l = s.charAt(left);
19+
char r = s.charAt(right);
20+
21+
//์™ผ์ชฝ์ด ์•ŒํŒŒ๋ฒณ or ์ˆซ์ž๊ฐ€ ์•„๋‹ˆ๋ฉด skip
22+
if (!Character.isLetterOrDigit(l)) {
23+
left += 1;
24+
continue;
25+
}
26+
//์˜ค๋ฅธ์ชฝ์ด ์•ŒํŒŒ๋ฒณ or ์ˆซ์ž๊ฐ€ ์•„๋‹ˆ๋ฉด skip
27+
if (!Character.isLetterOrDigit(r)) {
28+
right -= 1;
29+
continue;
30+
}
31+
if (Character.toLowerCase(l) != Character.toLowerCase(r) ) {
32+
return false;
33+
}
34+
left += 1;
35+
right -= 1;
36+
}
37+
38+
return answer;
39+
}
40+
}

0 commit comments

Comments
ย (0)