Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 61eaf8a

Browse files
Added solution for the Valid Palindrome problem
Signed-off-by: Krishna Kishore Shetty <kkshetty.work@pm.me>
1 parent 9416914 commit 61eaf8a

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

‎valid_palindrome/Notes.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
Original: https://leetcode.com/problems/valid-palindrome/solutions/5056369/simple-2-line-python3-solution-beats-91-on/
2+
3+
# Intuition
4+
We simply remove the unwanted characters from the string, convert to lowercase, and reverse the string and then compare to the original.
5+
6+
# Approach
7+
- Import the Python Regex module
8+
- Convert input string to lowercase
9+
- Use it remove the unwanted characters, which are all characters excluding letters and numbers
10+
- Now that we have the *cleaned* input string, compare it to the reversed version of itself, and return the result.
11+
12+
# Complexity
13+
- Time complexity:
14+
$$O(n)$$
15+
Note: This excludes the time taken by the Python Regex module(`re`) to match and substitute the unwanted characters from the input string.
16+
This [StackOverflow answer](https://stackoverflow.com/a/21702/2627137) says its $$O(2^m + n)$$, where m is length of regex string, and n is length of input string
17+
18+
Reversing the string is an O(n) operation. And so is string comparison.
19+
Therefore overall complexity exhibits linear growth along with size of input.
20+
21+
- Space complexity:
22+
$$O(n)$$
23+
24+
# Code
25+
```python
26+
import re
27+
28+
class Solution:
29+
def isPalindrome(self, s: str) -> bool:
30+
s_clean = re.sub('[^a-z0-9]','',s.lower())
31+
return s_clean==s_clean[::-1]
32+
```

‎valid_palindrome/Solution.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import re
2+
3+
class Solution:
4+
def isPalindrome(self, s: str) -> bool:
5+
s_clean = re.sub('[^a-z0-9]','',s.lower())
6+
return s_clean==s_clean[::-1]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /