Leetcode No.125 Valid Palindrome(c++实现)
2021/7/31 20:06:20
本文主要是介绍Leetcode No.125 Valid Palindrome(c++实现),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1. 题目
1.1 英文题目
Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
1.2 中文题目
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
1.3输入输出
输入 | 输出 |
---|---|
s = "A man, a plan, a canal: Panama" | true |
s = "race a car" | false |
1.4 约束条件
- 1 <= s.length <= 2 * 105
- s consists only of printable ASCII characters.
2. 分析
2.1 一般算法
简单粗暴,样例通过,但是测试超时
class Solution { public: bool isPalindrome(string s) { int i = 0, j = s.size() - 1; while (i < j) { while (s[i] < 65 || (s[i] > 90 && s[i] < 97) || s[i] > 122) { ++i; } while (s[j] < 65 || (s[j] > 90 && s[j] < 97) || s[j] > 122) { --j; } int temp = s[i] - s[j]; if (temp != 32 && temp != -32 && temp != 0) { return false; } ++i; --j; } return true; } };
2.2 大神算法
参考:https://leetcode.com/problems/valid-palindrome/discuss/40048/Here's-a-clean-C%2B%2B-solution
class Solution { public: bool isPalindrome(string s) { for (int i = 0, j = s.size() - 1; i < j; i++, j--) { // Move 2 pointers from each end until they collide while (isalnum(s[i]) == false && i < j) i++; // Increment left pointer if not alphanumeric while (isalnum(s[j]) == false && i < j) j--; // Decrement right pointer if no alphanumeric if (toupper(s[i]) != toupper(s[j])) return false; // Exit and return error if not match } return true; } };
注意:isalnum的用法:https://www.cplusplus.com/reference/cctype/isalnum/
这篇关于Leetcode No.125 Valid Palindrome(c++实现)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-06有没有什么开源的py项目可以对图像进行分类-icode9专业技术文章分享
- 2024-07-05feign默认connecttimeout和readtimeout是多少-icode9专业技术文章分享
- 2024-07-05idea控制台,日志太多,导致部分想看得日志被刷走 搜不到-icode9专业技术文章分享
- 2024-07-05The server selected protocol version Tls10 is not accepted by client preferences [TLs12]-icode9专业技术文章分享
- 2024-07-05怎么清理项目缓存-icode9专业技术文章分享
- 2024-07-04安装 Eyoucms详细图文教程-icode9专业技术文章分享
- 2024-07-04ueditor 复制文章时,图片的链接是一个下载图片地址,该如何处理?-icode9专业技术文章分享
- 2024-07-04怎样判断host有没有对wordpress有缓存呢-icode9专业技术文章分享
- 2024-07-04具有编译功能的系统make后,无法ssh连接-icode9专业技术文章分享
- 2024-07-04make后如何升级ssh-icode9专业技术文章分享