# C#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.

Input: “A man, a plan, a canal: Panama”

Output: true

Input: “race a car”

Output: false

```public class Program {

public static void Main(string[] args) {
var s = "0P";

var res = IsPalindrome(s);
Console.WriteLine(res);

s = "A man, a plan, a canal: Panama";

res = IsPalindrome2(s);
Console.WriteLine(res);

}

private static bool IsPalindrome(string s) {
//基本思路，反转字符串后判定和之前是否相同
//LeetCode超时未AC
s = FilterCharacter(s);
var reverse = "";
s.Reverse().ToList().ForEach(c => reverse += c);
return s == reverse;
}

/// <summary>
/// 过滤非字母以外的字符串
/// </summary>
/// <returns>过滤后的字符串</returns>
/// <param name="s">待过滤的字符串</param>
private static string FilterCharacter(string s) {
var res = string.Empty;
s = s.ToLower().Trim();
s.ToList().ForEach(c => {
if((c >= 48 && c <= 57) ||
(c >= 97 && c <= 122)) res += c;
});
return res;
}

private static bool IsPalindrome2(string s) {
//基本思路，先用List存放所有符合条件的字符
//再比较前半部分和后半部分
s = s.ToLower().Trim();
var list = new List<char>();
foreach(var c in s) {
if((c >= 48 && c <= 57) ||
(c >= 97 && c <= 122)) {
}
}
var mid = list.Count / 2;
for(var i = 0; i < mid; i++) {
if(list[i] != list[list.Count - i - 1]) return false;
}
return true;
}

}```

```False
True```

(1)