Skip to content

Commit 2e06dce

Browse files
committed
add valid-palindrome solution
1 parent affba32 commit 2e06dce

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
[Problem]
3+
https://leetcode.com/problems/valid-palindrome/description/
4+
5+
๋ชจ๋“  ๋Œ€๋ฌธ์ž๋ฅผ ์†Œ๋ฌธ์ž๋กœ ๋ณ€ํ™˜ํ•˜๊ณ  ์•ŒํŒŒ๋ฒณ๊ณผ ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๋ฌธ์ž๋“ค์„ ์ „๋ถ€ ์ œ๊ฑฐํ•˜ํ•œ ์ดํ›„์— ์•ž์—์„œ ๋ถ€ํ„ฐ ์ผ์œผ๋‚˜ ๋’ค์—์„œ ๋ถ€ํ„ฐ ์ฝ๋‚˜ ๋™์ผํ•˜๊ฒŒ ์ฝํžŒ๋‹ค๋ฉด, ๊ทธ ๋ฌธ์žฅ์€ ํšŒ๋ฌธ์ž…๋‹ˆ๋‹ค.
6+
์˜์ˆซ์ž ๋ฌธ์ž๋“ค์€ ์•ŒํŒŒ๋ฒณ๊ณผ ์ˆซ์ž๋“ค์„ ํฌํ•จํ•ฉ๋‹ˆ๋‹ค.
7+
8+
[Brainstorming]
9+
leftPosition๊ณผ rightPosition์„ ๋‘๊ณ , ๋น„๊ตํ•˜๋ฉด์„œ ์•„๋‹ ๊ฒฝ์šฐ false๋ฅผ returnํ•œ๋‹ค. => O(s.length)
10+
11+
[Complexity]
12+
N: s.length
13+
Time: O(1/2 * N) => O(N)
14+
Space: O(1)
15+
"""
16+
17+
class Solution:
18+
def isPalindrome(self, s:str)-> bool:
19+
leftPos, rightPos = 0, len(s) - 1
20+
while leftPos < rightPos:
21+
while not s[leftPos].isalnum() and leftPos < rightPos:
22+
leftPos += 1
23+
while not s[rightPos].isalnum() and leftPos < rightPos:
24+
rightPos -= 1
25+
26+
if s[leftPos].upper() != s[rightPos].upper():
27+
return False
28+
leftPos += 1
29+
rightPos -= 1
30+
return True
31+
32+
sol = Solution()
33+
print(sol.isPalindrome("A man, a plan, a canal: Panama") == True)
34+
print(sol.isPalindrome("race a car") == False)
35+
print(sol.isPalindrome(" ") == True)
36+
print(sol.isPalindrome("0P") == False)
37+
print(sol.isPalindrome("a") == True)

0 commit comments

Comments
ย (0)