您的位置:首页 > 其它

LeetCode125-验证回文串

2019-06-25 22:03 411 查看

1.题目描述

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。说明:本题中,我们将空字符串定义为有效的回文串

示例:

[code]示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true

示例 2:
输入: "race a car"
输出: false

示例 3:
输入: "0P"
输出: false

2.解题思路

扫描字符串,将字母(大写转换为小写)和数字压入栈,根据栈的特性判断是否为回文串。

3.代码实现

[code]class Solution {
public:
bool isPalindrome(string s) {
int len = s.length();
if (len <= 1)
return true;
stack<char> stk;
for (int i = 0; i < len; i++)
{
if (isalpha(s[i]))
{
if (isupper(s[i]))
{
s[i] = s[i] + 32; //大写变小写
}
stk.push(s[i]);
}
else if(isdigit(s[i]))
stk.push(s[i]);
}
for (int i = 0; i < len; i++)
{
if (isalpha(s[i]) || isdigit(s[i]))
{
char ch = stk.top();
stk.pop();
if (s[i] != ch)
return false;
}
}
return true;
}
};

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: