题目:https://leetcode-cn.com/problems/valid-palindrome/comments/
我的第一种方法:
用了正则表达式,提交有无法识别的关键字,不可取(正则不熟练)
public class Solution {
public bool IsPalindrome(string s) {
string strSplit1 = Regex.Replace(str, "[a-z]", "", RegexOptions.IgnoreCase);
char[] c = strSplit1.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
str = str.Replace(c[i].ToString(), "");
}
StringBuilder sb = new StringBuilder();
for (int i = str.Length-1; i>=0 ; i--)
{
sb.Append(str[i]);
}
string b = "" + sb;
if (b.Equals(str, StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
}
第二种方法;
效率不高,但是思想很6,是我同事王勇想出来的。
public class Solution {
public bool IsPalindrome(string s) {
if (s == null) return true;
s = s.ToLower();
StringBuilder str = new StringBuilder();
string sss = "";
foreach (var item in s.ToCharArray())
{
if ((item >= '0' && item <= '9') || (item >= 'a' && item <= 'z'))
{
str.Append(item);
sss = item + sss;
}
}
return str.ToString().Equals(sss);
}
}