[LintCode] Valid Palindrome 验证回文字符串
字符串 验证 回文 valid lintcode Palindrome
2023-09-11 14:21:37 时间
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Notice
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
"A man, a plan, a canal: Panama"
is a palindrome.
"race a car"
is not a palindrome.
Challenge
O(n) time without extra memory.
LeetCode上的原题,请参见我之前的博客Valid Palindrome。
解法一:
class Solution { public: /** * @param s A string * @return Whether the string is a valid palindrome */ bool isPalindrome(string& s) { int left = 0, right = s.size() - 1; while (left < right) { if (!isAlNum(s[left])) ++left; else if (!isAlNum(s[right])) --right; else if ((s[left] + 32 - 'a') % 32 != (s[right] + 32 - 'a') % 32) return false; else { ++left; --right; } } return true; } bool isAlNum(char c) { if (c >= 'a' && c <= 'z') return true; if (c >= 'A' && c <= 'Z') return true; if (c >= '0' && c <= '9') return true; return false; } };
解法二:
class Solution { public: /** * @param s A string * @return Whether the string is a valid palindrome */ bool isPalindrome(string& s) { int left = 0, right = s.size() - 1; while (left < right) { if (!isalnum(s[left])) ++left; else if (!isalnum(s[right])) --right; else if ((s[left] + 32 - 'a') % 32 != (s[right] + 32 - 'a') % 32) return false; else { ++left; --right; } } return true; } };
相关文章
- C语言字符串函数总结
- 是否以某字符串结尾 是否以某字符串开始 是否是整数 裁减字符串空格 是否是浮点数 是否所有字符为数字类型 是否为空 是否是EMAIL 是否是电话号码 身份证号码验证-支持新的带x身份证 日期验证
- Java实现 LeetCode 680 验证回文字符串 Ⅱ(暴力)
- Java实现 LeetCode 205 同构字符串
- 编写高质量代码改善C#程序的157个建议[为类型输出格式化字符串、实现浅拷贝和深拷贝、用dynamic来优化反射]
- 【栈&队列】LeetCode 394. 字符串编码【中等】
- C/C++基础讲解(八十三)之常见试题解答篇(序列排序/整数各位数字排序/字符串字母移位/Fibonacc数列)
- leetcode 1869. 哪种连续子字符串更长---滑动窗口篇3,双指针篇4
- C# 移除字符串末尾指定字符
- ZZNUOJ_用C语言编写程序实现1139:输出最短字符串(附完整源码)
- 练习 3-5 编写函数itob(n, s, b),将整数n转换为以b为底的数,并将转换结果以字符的形式保存到字符串s中。
- Leetcode 680. 验证回文字符串 Ⅱ(可以,已解决)
- spring接收json字符串的两种方式
- 定义一个字符串类,比较运算
- Python 工匠:使用数字与字符串的技巧学习笔记
- @ResponseBody 转化成json后与实体类字段名不一致_SpringMVC字符串解析成json对象(@RequestBody注解和@ResponseBody注解)