Advertisement
smj007

Untitled

Jul 31st, 2023
884
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. """
  2. So, if we start traversing inwards, from both ends of the input string, we can expect to see the same characters, in the same order.
  3.  
  4. The resulting algorithm is simple:
  5.  
  6. - Set two pointers, one at each end of the input string-
  7. - If the input is palindromic, both the pointers should point to equivalent characters, at all times. 1
  8. - If this condition is not met at any point of time, we break and return early.
  9. - We can simply ignore non-alphanumeric characters by continuing to traverse further.
  10. - Continue traversing inwards until the pointers meet in the middle.
  11. """
  12.  
  13. class Solution:
  14.     def isPalindrome(self, s: str) -> bool:
  15.  
  16.         def is_alphabet(c):
  17.             return ord(c) - ord("a") < 26 or ord(c) - ord("A") < 26
  18.  
  19.         if len(s) == 1:
  20.             return is_alphabet(s[0])
  21.  
  22.         if len(s) == 0:
  23.             return False
  24.  
  25.         start = 0
  26.         end = len(s) - 1
  27.  
  28.         while (start<end):
  29.             if not is_alphabet(s[start]):
  30.                 start = start+1
  31.                 continue
  32.  
  33.             if not is_alphabet(s[end]):
  34.                 end = end - 1
  35.                 continue
  36.  
  37.             if s[start].lower() == s[end].lower():
  38.                 start = start + 1
  39.                 end = end - 1
  40.                 continue
  41.             else:
  42.                 return False
  43.  
  44.         return True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement