--- tags: LeetCode --- # 125. Valid Palindrome Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false 輸入範本如下 ```C# public class Solution { public bool IsPalindrome(string s) { } } ``` ### 直覺想法 這題只需要判斷 '大小寫 or 數字' , 因此需要一個方式去判斷字元是否為大小寫數字. 若非大小寫數字則忽略. 使用兩個指標去指 , 看看所指的這兩個字是否相同 , 若不同 , 則此字串非迴文 , 若相同則繼續比 . 若全部比完皆相同 , 則此字串為迴文 ps : 題目的大小寫視為相同字元 ```C# 72 ms 24.7 MB You are here! Your runtime beats 95.70 % of csharp submissions. public bool IsPalindrome(string s) { s = s.ToLower(); // 全部轉成小寫 , 就不用區分是否大小寫了 bool ans = true; for (int left = 0, right = s.Length - 1; left < right; left++, right--) { while (left < right && !char.IsLetterOrDigit(s[left])) { left++; } while (left < right && !char.IsLetterOrDigit(s[right])) { right--; } if (s[left] != s[right]) { return false; } } return ans; } ``` ```C# 72 ms 24.4 MB You are here! Your runtime beats 95.70 % of csharp submissions. public bool IsPalindrome(string s) { bool ans = true; for (int left = 0, right = s.Length - 1; left < right; left++, right--) { while (left < right && !IsLetterOrDigit(s[left])) { left++; } while (left < right && !IsLetterOrDigit(s[right])) { right--; } if (!IsSame(s[left], s[right])) { return false; } } return ans; bool IsLetterOrDigit(char c) => (c <= 'Z' && c >= 'A') || (c <= 'z' && c >= 'a') || (c <= '9' && c >= '0'); bool IsSame(char a, char b) => char.ToLower(a) == char.ToLower(b); } ``` ### Thank you! You can find me on - [GitHub](https://github.com/s0920832252) - [Facebook](https://www.facebook.com/fourtune.chen) 若有謬誤 , 煩請告知 , 新手發帖請多包涵 # :100: :muscle: :tada: :sheep: