114 lines
3.6 KiB
Python
114 lines
3.6 KiB
Python
"""
|
|
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
|
|
|
|
Given a string s, return true if it is a palindrome, or false otherwise.
|
|
|
|
Example 1:
|
|
Input: s = "A man, a plan, a canal: Panama"
|
|
Output: true
|
|
Explanation: "amanaplanacanalpanama" is a palindrome.
|
|
|
|
Example 2:
|
|
Input: s = "race a car"
|
|
Output: false
|
|
Explanation: "raceacar" is not a palindrome.
|
|
|
|
Example 3:
|
|
Input: s = " "
|
|
Output: true
|
|
Explanation: s is an empty string "" after removing non-alphanumeric characters.
|
|
Since an empty string reads the same forward and backward, it is a palindrome.
|
|
"""
|
|
|
|
"""
|
|
0. Edge кейсы
|
|
- Один символ -> return True
|
|
- Вся строка не из валидных символов -> return True
|
|
|
|
1. Сначала делаем всю строку в lowercase
|
|
|
|
Затем надо определить как убирать все невалидные элементы
|
|
Из условия можно выделить:
|
|
Alphanumeric characters include letters and numbers.
|
|
Как можно определить слова?
|
|
- Метод ord(char). Только я не помню промежуток латинских букв и цифр.
|
|
Подсмотрев понял, что ord(char) должен быть либо в промежутке от 48 до 57 или от 97 до 122
|
|
|
|
2. Ставим два указателя на начало и конец строки
|
|
Начинаем итерацию
|
|
3.1
|
|
|
|
a man, a plan, a canal: panama
|
|
i j
|
|
|
|
i = 0 s[i] = "a"
|
|
j = len(s) - 1 s[j] = "a"
|
|
|
|
Проверяем их на валидность:
|
|
"a" - валидные символы
|
|
Проверяем их на сходство:
|
|
"a" == "a" -> continue
|
|
|
|
Двигаем i на шаг влево, j на шаг назад
|
|
|
|
----------------------------------------
|
|
|
|
a man, a plan, a canal: panama
|
|
i j
|
|
|
|
i = 0 s[i] = " "
|
|
j = len(s) - 1 s[j] = "m"
|
|
|
|
Проверяем их на валидность:
|
|
s[i] = " " - не валидный символ, сдвигаем i вправо
|
|
s[i] = "m" - валидный символ, останавливаемя
|
|
s[j] = "m" - валидный симовл
|
|
Проверяем их на сходство:
|
|
"m" == "m" -> continue
|
|
|
|
Двигаем i на шаг влево, j на шаг назад
|
|
----------------------------------------
|
|
|
|
"""
|
|
|
|
class Solution:
|
|
def isPalindrome(self, s: str) -> bool:
|
|
def check_validity(c: str) -> bool:
|
|
nums = [num for num in range(48, 58)]
|
|
chars = [char for char in range(97, 123)]
|
|
if ord(c) in nums or ord(c) in chars:
|
|
return True
|
|
else:
|
|
return False
|
|
# edge case 1
|
|
if len(s) == 1:
|
|
return True
|
|
i = 0
|
|
j = len(s) - 1
|
|
while i < j:
|
|
left_char = s[i].lower()
|
|
right_char = s[j].lower()
|
|
if not check_validity(left_char):
|
|
i += 1
|
|
continue
|
|
if not check_validity(right_char):
|
|
j -= 1
|
|
continue
|
|
if not ord(left_char) == ord(right_char):
|
|
return False
|
|
i += 1
|
|
j -= 1
|
|
return True
|
|
|
|
cl = Solution()
|
|
s = "A man, a plan, a canal: Panama"
|
|
res = True
|
|
print(f"{cl.isPalindrome(s)} == {res}")
|
|
|
|
s = "race a car"
|
|
res = False
|
|
print(f"{cl.isPalindrome(s)} == {res}")
|
|
|
|
s = " "
|
|
res = True
|
|
print(f"{cl.isPalindrome(s)} == {res}")
|