Skip to content

Commit 9694699

Browse files
committed
feat : valid palindrome
1 parent d1f7750 commit 9694699

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

valid-palindrome/ekgns33.java

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
start : 7:18 ~
3+
input : String s
4+
output : return if given s is valid palindrome
5+
constraint:
6+
1) valid palindrome?
7+
convert all uppercase letter to lowercase,
8+
remove non-alphanumeric chars,
9+
reads same forward and backward.
10+
ex) abba, aba, a, aacbcaa
11+
2) length of the input string
12+
[1, 2*10^5]
13+
3) does input string contains non-alphanumeric chars? such as whitespace
14+
yes, but only ASCII chars
15+
16+
-------
17+
18+
brute force:
19+
read each character of input string.
20+
create a new string that only contains
21+
lowercase letters and numbers << O(n), when n is length of string s
22+
23+
create string which one is reversed. < O(n)
24+
25+
compare. < O(n)
26+
27+
time : O(n)-3loops, space : O(n)
28+
29+
-------
30+
better : two-pointer
31+
32+
same as brute force. build new string.
33+
34+
use two pointer left and right
35+
36+
while left <= right
37+
if s[left] != s[right] return false;
38+
39+
return true;
40+
-------
41+
optimal :
42+
43+
use two pointer left and right
44+
while left <= right
45+
if s[left] is non-alpha left++
46+
elif s[right] is non-alpha right--
47+
elif s[left] != s[right] return false
48+
else left++ right--
49+
50+
return true
51+
time : O(n) space : O(1)
52+
*/
53+
class Solution {
54+
public boolean isPalindrome(String s) {
55+
int left = 0;
56+
int right = s.length() - 1;
57+
char leftC;
58+
char rightC;
59+
while(left <= right) {
60+
leftC = s.charAt(left);
61+
rightC = s.charAt(right);
62+
if(!Character.isLetterOrDigit(leftC)) {
63+
left++;
64+
} else if (!Character.isLetterOrDigit(rightC)) {
65+
right--;
66+
} else if (Character.toLowerCase(leftC) != Character.toLowerCase(rightC)) {
67+
return false;
68+
} else {
69+
left++;
70+
right--;
71+
}
72+
}
73+
return true;
74+
}
75+
}

0 commit comments

Comments
 (0)