125. 验证回文串
2019-05-23 11:34
246 查看
题目
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: “A man, a plan, a canal: Panama”
输出: true
示例 2:
输入: “race a car”
输出: false
分析
思路比较简单,双指针可以很容易解决这个问题
需要注意的是,我们用相减的绝对值等于32忽略大小写之前,不要忘记先把数字的情况分离出去
否则可能造成’0’acsll码48 'P’acsll码80 相减等于32的错误,这并不是忽略大小写
时间复杂度O(N)
空间复杂度O(1)
代码
public bool IsPalindrome(string s) { if (s == null) { return false; } int point = 0;//指针1 从起点开始 int point1 = s.Length - 1;//指针2 从终点开始 while (point < point1) { //不满足该字符是数字 大写字母 或小写字母 并且没有越界 while (point < point1 && !((s[point] >= 48 && s[point] <= 57) || (s[point] >= 65 && s[point] <= 90) || (s[point] >= 97 && s[point] <= 122))) { point++; } //不满足该字符是数字或者字母 while (point < point1 && !((s[point1] >= 48 && s[point1] <= 57) || (s[point1] >= 65 && s[point1] <= 90) || (s[point1] >= 97 && s[point1] <= 122))) { point1--; } //s[point]或s[point1]是数字 if ((s[point] >= 48 && s[point] <= 57) || (s[point1] >= 48 && s[point1] <= 57)) { if (s[point] != s[point1]) { return false; } } //两个都不是数字 也就是两个都是字母 else { //如果两个字符不相同 并且两个字母忽略大小写仍然不相同 if (s[point] != s[point1] && (s[point] > s[point1] ? s[point] - s[point1] : s[point1] - s[point]) != 32) { return false; } } point++; point1--; } return true; }
相关文章推荐
- LeetCode125-验证回文串
- 125. 验证回文串 Java
- leetcode 125 验证回文串
- LeetCode 125.验证回文串
- LeetCode-125.验证回文串(相关话题:字符串)
- [leetcode]验证回文串[javascript]
- 验证回文串
- leetcode-125. Valid Palindrome(验证含有标点符号String是否为回文串)
- Leetcode:125.验证回文串
- 【LeetCode-面试算法经典-Java实现】【125-Valid Palindrome(回文字验证)】
- Lettcode_125_Valid Palindrome ——判断字符串是否为回文串
- 验证字符串是否为数字字符串。如‘125’,‘2313.12’等为数字字符串的方法
- 验证回文串 - LeetCode
- 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写
- 验证回文串(java)
- 验证回文串--leetcode第125题
- 这个题目让我很迷--验证回文串--Java
- LeetCode 125. 验证回文串
- 验证回文串(忽略空格和标点以及大小写)
- Leetcode刷题28-125.验证回文串(C++)