檢查檢查數字英文正反向是否相同, 忽略其它符號
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 letters and numbers.
Given a string s
, return true
if it is a palindrome, or false
otherwise.Taiwan is a country. 臺灣是我的國家
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.
Constraints:
1 <= s.length <= 2 * 105
s
consists only of printable ASCII characters.
檢查數字英文正反向不分大小寫是否相同, 要忽略其它符號,
簡單的作法可以用Regex先去掉不需要的再全轉小寫,如下:
public bool IsPalindrome(string s)
{
s = System.Text.RegularExpressions.Regex.Replace(s, @"[^a-zA-Z0-9]", "").ToLower();
for (int i = 0, j = s.Length - 1; j > i; i++, j--)
if (s[i] != s[j])
return false;
return true;
}
若不想用內建功能, 可以手動比對如下Char:
a~z : 97~122
A~Z : 65~90
0~9 : 48~57
大小寫差32
public bool IsPalindrome(string s)
{
for (int i = 0, j = s.Length - 1; j > i; i++, j--)
{
int x, y;
while ((x = GetChar(s, i)) == 0 && i < j)
i++;
while ((y = GetChar(s, j)) == 0 && i < j)
j--;
if (x != y)
return false;
}
return true;
}
private int GetChar(string s, int idx)
{
int c = (int)s[idx];
if (c >= 97 && c <= 122)
return c - 32;
if ((c >= 65 && c <= 90) || (c >= 48 && c <= 57))
return c;
return 0;
}
Taiwan is a country. 臺灣是我的國家