1.问题描述
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.
Example 1:
Input: “A man, a plan, a canal: Panama”
Output: true
Example 2:
Input: “race a car”
Output: false
来自https://leetcode.com/problems/valid-palindrome/description/
2.题目分析
判断一个字符串是否是“回文”,即除去符号,只保留数字和字母后,顺序看和倒序看都一样,这个挺有意思的。比较简单的方法就是,新建一个字符串,取出所有的字母和数字,并把字母全部转成小写的,再判断新生成的字符串是否是对称的。当然,这种方法的效率是比较低的。
3.C++代码
//我的代码:(beats 5%)
bool isPalindrome(string s)
{
string s1 = "";
for (int i = 0; i < s.length(); i++)
{
if (s[i] >= 'a' && s[i] <= 'z')
s1 += s[i];
if (s[i] >= 'A' && s[i] <= 'Z')
s1 += (s[i]+32);
if(s[i] >= '0' && s[i] <= '9')
s1 += s[i];
}
int l = s1.length();
if (l < 2)
return true;
for (int i = 0; i <=l/2 ; i++)
{
if (s1[i] != s1[l-1-i])
return false;
}
return true;
}
//改进后的代码:(beats 36%)
bool isValid(char &c) //判断是否是字母或者数字
{
if (c >= 'a' && c <= 'z')return true;
if (c >= '0' && c <= '9') return true;
if (c >= 'A' && c <= 'Z') { c = c + 32; return true; }//大写转小写
return false;
}
bool isPalindrome(string s)
{
if (s.empty())
return true;
int i = 0;
int j = s.length()-1;
while (i < j)
{
bool f1 = 0;
bool f2 = 0;
if (!isValid(s[i]))
{
i++;
continue;//
}
if (!isValid(s[j]))
{
j--;
continue;//
}
if (s[i] != s[j])//比较
return false;
i++;
j--;
}
return true;
}
//别人家的代码,思路差不多
bool isPalindrome(string s) {
if (s.empty()) return true;
else
{
auto pf = s.begin(), pl = s.end() - 1;
while (pf<pl)
{
if (isalnum(*pf) && isalnum(*pl))
{
if (tolower(*pf) == tolower(*pl))
{
pf++;
pl--;
continue;
}
else
return false;
}
else
{
if (!isalnum(*pf)) pf++;
if (!isalnum(*pl)) pl--;
}
}
return true;
}
}
4.continue的用法
continue语句的作用是:结束当前正在执行的这一次循环(for、while、do…while),接着执行下一次循环。即跳过循环体中尚未执行的语句,接着进行下一次是否执行循环的判定。
for (int i = 0; i < 10:i++)
{
if (i == 3) break;
cout << i << endl;
}//输出0,1,2
for (int i = 0; i < 10:i++)
{
if (i == 3) continue;
cout << i << endl;
}//输出0,1,2,4,5,6,7,8,9