From a1bd06c84b438b48a6c01fb1b14d74571752cf50 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Thu, 27 Feb 2025 12:00:57 -0700 Subject: 125. valid palindrome --- valid_palindrome.c | 35 +++++++++++++++++++++++++++++++++++ valid_palindrome.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 valid_palindrome.c create mode 100644 valid_palindrome.py diff --git a/valid_palindrome.c b/valid_palindrome.c new file mode 100644 index 0000000..d3dfe81 --- /dev/null +++ b/valid_palindrome.c @@ -0,0 +1,35 @@ +// 125. Valid Palindrome +#include "leetcode.h" + +/* + * 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 only letters and + * numbers. given a string 's', return true if it is a palindrome, or false + * otherwise. + */ + +bool isPalindrome(char *s) { + int l = 0, r = strlen(s) - 1; + while (l < r) { + if (isalnum(s[l])) { + if (isalnum(s[r])) { + if (tolower(s[l]) != tolower(s[r])) + return false; + l++, r--; + } else + r--; + } else + l++; + } + return true; +} + +int main() { + char *s1 = "A man, a plan, a canal: Panama"; + char *s2 = "race a car"; + char *s3 = " "; + printf("%d\n", isPalindrome(s1)); // expect: 1 + printf("%d\n", isPalindrome(s2)); // expect: 0 + printf("%d\n", isPalindrome(s3)); // expect: 1 +} diff --git a/valid_palindrome.py b/valid_palindrome.py new file mode 100644 index 0000000..2b361e0 --- /dev/null +++ b/valid_palindrome.py @@ -0,0 +1,35 @@ +# 125. Valid Palindrome + +""" +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 only letters and +numbers. given a string 's', return true if it is a palindrome, or false +otherwise. +""" + + +class Solution(object): + def isPalindrome(self, s): + """ + :type s: str + :rtype: bool + """ + l, r = 0, len(s) - 1 + while l < r: + while l < r and not s[l].isalnum(): + l += 1 + while l < r and not s[r].isalnum(): + r -= 1 + if s[l].lower() != s[r].lower(): + return False + l += 1 + r -= 1 + return True + + +if __name__ == "__main__": + obj = Solution() + print(obj.isPalindrome(s="A man, a plan, a canal: Panama")) + print(obj.isPalindrome(s="race a car")) + print(obj.isPalindrome(s=" ")) -- cgit v1.2.3