leetcode:字符串之Valid Palindrome
回文编程思想:先判断给定字符串的首尾字符是否相等,若相等,则判断去掉首尾字符后的字符串是否为回文,若不相等,则该字符串不是回文
题目:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
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 is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
即:检测字符串是否为回文数。与数字回文不同的是,题目中给出的英文句子/短语包含空格及标点符号,因此需要在算法设计时加多一层判断。
C++实现:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
bool isPalindrome(string s)
{
transform(s.begin(), s.end(), s.begin(), tolower);
if (s.empty())
return true;
auto left = s.begin(), right = prev(s.end());
while (left < right)
{
if (!isalpha(*left))
left++;
else if (!isalpha(*right))
right--;
else if (*left == *right)
{
left++;
right--;
}
else return false;
}
return true;
}
int main()
{
string s="A man, a plan, a canal: Panama";
// string s="race a car";
// string s="";
cout<<s<<endl;
bool vp;
vp=isPalindrome(s);
if(vp)
cout<<s<<" :is a palindrome"<<endl;
else
cout<<s<<" :is not a palindrome"<<endl;
return 0;
}
测试结果:
leetcode:Palindrome Number
题目:
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem ”Reverse Integer”,
you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
即:判断数字回文。解法是,不断地取第一位和最后一位(10 进制下)进行比较,相等则取第二位和倒数第
二位,直到完成比较或者中途找到了不一致的位。
c++实现:
#include <iostream>
using namespace std;
bool isPalindrome(int x)
{
if (x < 0)
return false;
int d = 1; // divisor
while (x / d >= 10)
d *= 10;
while (x > 0)
{
int q = x / d; // quotient
int r = x % 10; // remainder
if (q != r)
return false;
x = x % d / 10;
d /= 100;
}
return true;
}
int main()
{
int x=1234321;
// int x=1234567;
bool pn;
pn=isPalindrome(x);
if(pn)
cout<<x<<" :is a palindrome"<<endl;
else
cout<<x<<" :is not a palindrome"<<endl;
return 0;
}
测试结果: