forked from Kyrylo-Ktl/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValid Palindrome II.py
49 lines (39 loc) · 1.23 KB
/
Valid Palindrome II.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution:
"""
Time: O(n)
Memory: O(1)
"""
def validPalindrome(self, string: str) -> bool:
n = len(string)
for i in range(n // 2):
j = n - 1 - i
if string[i] != string[j]:
return self.is_palindrome(string, i, j - 1) or \
self.is_palindrome(string, i + 1, j)
return True
@staticmethod
def is_palindrome(string: str, start: int, end: int) -> bool:
for i in range((end - start + 1) // 2):
if string[start + i] != string[end - i]:
return False
return True
class Solution:
"""
Time: O(n)
Memory: O(1)
"""
def validPalindrome(self, string: str) -> bool:
i, j = 0, len(string) - 1
while i < j:
if string[i] != string[j]:
return self.is_palindrome(string, i, j - 1) or \
self.is_palindrome(string, i + 1, j)
i += 1
j -= 1
return True
@staticmethod
def is_palindrome(string: str, start: int, end: int) -> bool:
for i in range((end - start + 1) // 2):
if string[start + i] != string[end - i]:
return False
return True