classSolution { public: boolisPalindrome(string s){ string sgood; for (char ch: s) { if (isalnum(ch)) { sgood += tolower(ch); } } int n = sgood.size(); int left = 0, right = n - 1; while (left < right) { if (sgood[left] != sgood[right]) { returnfalse; } ++left; --right; } returntrue; } };
[sol12-Python3]
1 2 3 4 5 6 7 8 9 10 11
classSolution: defisPalindrome(self, s: str) -> bool: sgood = "".join(ch.lower() for ch in s if ch.isalnum()) n = len(sgood) left, right = 0, n - 1 while left < right: if sgood[left] != sgood[right]: returnFalse left, right = left + 1, right - 1 returnTrue
classSolution { public: boolisPalindrome(string s){ int n = s.size(); int left = 0, right = n - 1; while (left < right) { while (left < right && !isalnum(s[left])) { ++left; } while (left < right && !isalnum(s[right])) { --right; } if (left < right) { if (tolower(s[left]) != tolower(s[right])) { returnfalse; } ++left; --right; } } returntrue; } };
[sol2-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defisPalindrome(self, s: str) -> bool: n = len(s) left, right = 0, n - 1 while left < right: while left < right andnot s[left].isalnum(): left += 1 while left < right andnot s[right].isalnum(): right -= 1 if left < right: if s[left].lower() != s[right].lower(): returnFalse left, right = left + 1, right - 1
funcisPalindrome(s string)bool { s = strings.ToLower(s) left, right := 0, len(s) - 1 for left < right { for left < right && !isalnum(s[left]) { left++ } for left < right && !isalnum(s[right]) { right-- } if left < right { if s[left] != s[right] { returnfalse } left++ right-- } } returntrue }