125. 验证回文串 (两边切和一边切)
2020-07-13 05:16
176 查看
题目:
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
解法1:处理双指针,直至都遇到数字字母
[code]class Solution { public: bool isPalindrome(string s) { int len = s.length(); if (len < 2) return true; int left = 0, right = len-1; while (left < right) { while (left < right && !isalnum(s[left])) left++; while (left < right && !isalnum(s[right])) right--; if (tolower(s[left]) != tolower(s[right])) return false; left++; right--; } return true; } };
这种解法,无效字符比较多的时候,比较次数较少
解法2:每次只处理一边指针
[code]class Solution { public: bool isPalindrome(string s) { int len = s.length(); if (len < 2) return true; int left = 0, right = len-1; while (left < right) { if (!isalnum(s[left])) left++; else if (!isalnum(s[right])) right--; else { if (tolower(s[left]) != tolower(s[right])) return false; left++; right--; } } return true; } };
这道题如果熟悉库函数的话写的会比较简单,否则就显得比较繁琐。
附录:
字母(不区分大小写):isalpha();
大写字母:isupper();
小写字母:islower();
数字:isdigit();
字母和数字:isalnum();
转化为大写:toupper();
转化为小写:tolower();
其中对于tolower():
1:函数声明:int tolower(int c)
2:返回值:如果 c 有相对应的小写字母,则该函数返回 c 的小写字母,否则 c 保持不变。返回值是一个可被隐式转换为 char 类型的 int 值。
相关文章推荐
- 125、验证回文串
- 125. 验证回文串
- 125. 验证回文串
- 125. 验证回文串 Java
- 【LeetCode-cpp】【37】125-验证回文串 Valid Palindrome
- LeetCode125-验证回文串
- leetcode 125 验证回文串
- leetcode-125-验证回文串
- leetcode-125-验证回文串
- leetcode(js)-每日一练之 验证回文串 题库编号125
- *验证回文串(leetcode)
- Leetcode:125.验证回文串
- 验证回文串和验证回文字符串Ⅱ
- LeetCode 125.验证回文串
- 验证回文串
- Codeforces 707C Pythagorean Triples(已知直角三角形一边求另两边)
- LeetCode - 125. 验证回文串
- Leetcode 125. 验证回文串
- 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写
- LeetCode 125. 验证回文串