原题网址:https://www.lintcode.com/problem/valid-palindrome/description面试
给定一个字符串,判断其是否为一个回文串。只考虑字母和数字,忽略大小写。markdown
你是否考虑过,字符串有多是空字符串?这是面试过程当中,面试官经常会问的问题。app
在这个题目中,咱们将空字符串断定为有效回文。函数
"A man, a plan, a canal: Panama"
是一个回文。spa
"race a car"
不是一个回文。.net
O(n) 时间复杂度,且不占用额外空间。指针
class Solution { public: /** * @param s: A string * @return: Whether the string is a valid palindrome */ bool isPalindrome(string &s) { // write your code here int n=s.size(); if (n==0) { return true; } int i=0,j=n-1; while(i<=j) { if (tmp(s[i])&&tmp(s[j])) { if (!isSame(s[i],s[j])) { return false; } } if (!tmp(s[i])) { i++; continue; } if (!tmp(s[j])) { j--; continue; } i++; j--; } return true; } bool tmp(char c) { if ((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c>='0'&&c<='9')) { return true; } return false; } bool isSame(char c1,char c2) { if (c1==c2) { return true; }
if (abs(c1-c2)==abs('a'-'A')) { return true; } return false; } };