Skip to content

Commit 5d3df3d

Browse files
committed
[First week][valid-palindrome] adds answer
1 parent 4f4795b commit 5d3df3d

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

valid-palindrome/routiful.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# FIRST WEEK
2+
3+
# Question : 125. Valid Palindrome
4+
5+
# A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and
6+
# removing all non-alphanumeric characters, it reads the same forward and backward.
7+
# Alphanumeric characters include letters and numbers.
8+
# Given a string s, return true if it is a palindrome, or false otherwise.
9+
10+
# Example 1:
11+
# Input: s = "A man, a plan, a canal: Panama"
12+
# Output: true
13+
# Explanation: "amanaplanacanalpanama" is a palindrome.
14+
15+
# Example 2:
16+
# Input: s = "race a car"
17+
# Output: false
18+
# Explanation: "raceacar" is not a palindrome.
19+
20+
# Example 3:
21+
# Input: s = " "
22+
# Output: true
23+
# Explanation: s is an empty string "" after removing non-alphanumeric characters.
24+
# Since an empty string reads the same forward and backward, it is a palindrome.
25+
26+
# Constraints:
27+
# 1 <= s.length <= 2 * 105
28+
# s consists only of printable ASCII characters.
29+
30+
# Notes:
31+
# Using `reverse`(O(N)) api and matching all(max O(N)) look straightforward.
32+
# The two pointer method may useful to decrease time complexity.
33+
# If length of input is 0 or 1, return true.
34+
35+
class Solution:
36+
def isPalindrome(self, s: str) -> bool:
37+
l = len(s)
38+
if l < 2:
39+
return True
40+
41+
f = 0
42+
b = l - 1
43+
44+
while (f <= b):
45+
if (s[f] == " " or (s[f].isalpha() == False and s[f].isnumeric() == False)):
46+
f = f + 1
47+
continue
48+
49+
if (s[b] == " " or (s[b].isalpha() == False and s[b].isnumeric() == False)):
50+
b = b - 1
51+
continue
52+
53+
if s[f].lower() != s[b].lower():
54+
return False
55+
56+
f = f + 1
57+
b = b - 1
58+
59+
return True

0 commit comments

Comments
 (0)