LeetCode 125. 验证回文串
2019-03-01 10:16
477 查看
- 题目:
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: “A man, a plan, a canal: Panama”
输出: true
示例 2:
输入: “race a car”
输出: false
- 解题思路
1.首先将字符串中所有字符字母压入数组中。然后判断向量的长度。
2 若长度为偶数。则从正中间两端开始比较,若都为字母,将其转化为大写字母比较,若都为数字,直接比较,否则返回false; - 若长度为奇数。则从正中间元素两端开始比较,若都为字母,将其转化为大写字母比较,若都为数字,直接比较,否则返回false;
用到的C++标准库函数:
isalpha(ch) 判断ch是否为字母
isdigit(ch) 判断ch是否为数字
toupper(ch) 将字母转化为大写字母
代码实现:
bool isPalindrome(string s) { vector<char> res; for(auto ch:s) { if(isalpha(ch) ||isdigit(ch)) res.push_back(ch); } int n1 = res.size(); if(n1 == 0 || n1 == 1) return true; cout << n1; if(n1 % 2 == 0) { //字母长度为偶数 for(int i = n1/2-1,j = n1/2; i>=0, j <n1; i--,j++) if(isalpha(res[i]) && isalpha(res[j])){ if(toupper(res[i]) != toupper(res[j])) return false; } else if(isdigit(res[i]) && isdigit(res[j])) { if(res[i] != res[j]) return false; } else return false; } else { //字母长度为奇数 for(int i =n1/2-1, j = n1/2+1;i>=0, j <n1;i--,j++) if(isalpha(res[i]) && isalpha(res[j])){ if(toupper(res[i]) != toupper(res[j])) return false; } else if(isdigit(res[i]) && isdigit(res[j])) { if(res[i] != res[j]) return false; } else return false; } return true; }
相关文章推荐
- LeetCode - 125. 验证回文串
- LeetCode-125.验证回文串(相关话题:字符串)
- Leetcode:125.验证回文串
- Leetcode刷题28-125.验证回文串(C++)
- [leetcode]验证回文串[javascript]
- 验证回文串 - LeetCode
- Leetcode题库 - 验证回文串(java语言版)
- LeetCode 125. Valid Palindorme (验证回文字符串)
- leetcode-125. Valid Palindrome(验证含有标点符号String是否为回文串)
- leetcode Valid Parentheses 验证括号
- LeetCode 242. Valid Anagram (验证变位词)
- [LeetCode] Validate IP Address 验证IP地址
- [LeetCode] 409. 最长回文串
- 【LeetCode】#131分割回文串(Palindrome Partitioning)
- Leetcode 409. Longest Palindrome 构造最长回文串 解题报告
- LeetCode 680. Valid Palindrome II (验证回文字符串 Ⅱ)
- Leetcode 367. Valid Perfect Square 平方数验证
- LeetCode | 5. Longest Palindromic Substring 回文串技巧
- leetcode-409. Longest Palindrome 最长回文串的长度
- [LeetCode] Valid Number 验证数字