首页 > 代码库 > [leetcode] 1. Valid Palindrome

[leetcode] 1. Valid Palindrome

leetcode的第一题,回文数判断。

原题如下:

 

For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome.

 

Note: Have you consider that the string might be empty? This is a good question to ask during an interview.

 

For the purpose of this problem, we define empty string as valid palindrome.

 

回文数是个很基础的东西,这里给了两个example作为提示:给的样本中可能会有空格,标点和特殊符号等,要考虑一下先判断string是否是纯string再去进行回文判断。

leetcode给的答案是伪代码,也解释的很清楚:

 

public boolean isPalindrome(String s) {    int i = 0, j = s.length() - 1;    while (i < j)         {        while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;        while (i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;                if (Character.toLowerCase(s.charAt(i))            != Character.toLowerCase(s.charAt(j)))                 {            return false;        }        i++; j--;    }    return true;}    

 

思路结束,具体在操作的时候就是C++的能力本身了。随手写的代码(日后改)[2014-11-09]:

#include <string>#include <algorithm>bool isPalindrome(string s) {    if (s.empty())    {        return false;    }    string tmp = "";    for (int i = 0; i < s.size(); i++)    {        if (isalnum(s.at(i)))        {            tmp += s[i];        }    }    transform(tmp.begin(), tmp.end(), tmp.begin(), ::toupper);    for (int i = 0; i < tmp.size() / 2; i++)    {        if (tmp.at(i) != tmp.at(tmp.size() - 1 - i))        {            return false;        }    }    return true;}


C++水平还不够,但是过了。回文的问题以后再补充。

 

[leetcode] 1. Valid Palindrome