[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 = , j = s.length() - ; 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 = ; i < s.size(); i++)
{
if (isalnum(s.at(i)))
{
tmp += s[i];
}
}
transform(tmp.begin(), tmp.end(), tmp.begin(), ::toupper);
for (int i = ; i < tmp.size() / ; i++)
{
if (tmp.at(i) != tmp.at(tmp.size() - - i))
{
return false;
}
} return true;
}

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

上一篇:Show Users Assigned to a Specific Role


下一篇:【30集iCore3_ADP出厂源代码(ARM部分)讲解视频】30-10底层驱动之I2C