Skip to content

Commit 80a4899

Browse files
committed
add solution valid palindrome
1 parent b61d5b0 commit 80a4899

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

valid-palindrome/JonghunLee.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import re
2+
3+
4+
# Time Complexity O(n)
5+
# - Both normal preprocessing and two-pointer comparisons have time complexity proportional to the length of the input string.
6+
# Space Complexity O(n)
7+
# - The space of the new string joined_string preprocessed from the input string is proportional to the length of the input string.
8+
9+
class Solution:
10+
def isPalindrome(self, s: str) -> bool:
11+
# Pre-processing using regular expression
12+
joined_string = re.sub(r"[^a-zA-Z]", "", s.lower())
13+
str_length = len(joined_string)
14+
15+
16+
# for loop n/2, two pointer for verify same or not
17+
for i in range(str_length // 2):
18+
end = str_length - i - 1
19+
if not self.check_palindrome(i, end, joined_string):
20+
return False
21+
22+
return True
23+
24+
def check_palindrome(self, i, end, joined_string) -> bool:
25+
left = joined_string[i]
26+
right = joined_string[end]
27+
28+
if left == right:
29+
return True
30+
else:
31+
return False
32+
33+
if __name__ == "__main__":
34+
solution = Solution()
35+
36+
# test case
37+
test_string = [
38+
"A man, a plan, a canal: Panama", # True (회문)
39+
"race a car", # False (회문 아님)
40+
" ", # True (빈 문자열도 회문으로 간주)
41+
"abba", # True (회문)
42+
"abcba", # True (회문)
43+
]
44+
45+
for index, test in enumerate(test_string):
46+
print(f"start {index} test")
47+
print(f"input : {test}")
48+
print(f"Is valid palindrome ? {solution.isPalindrome(test)}\n")
49+
50+
51+

0 commit comments

Comments
 (0)