首页 > 代码库 > leetcode[125] Valid Palindrome
leetcode[125] Valid Palindrome
判断一个字符串是不是回文,忽略其中的非数字和非字母,例如符号和空格不考虑。
For example,"A man, a plan, a canal: Panama"
is a palindrome."race a car"
is not a palindrome.
Note:
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.
想到用reverse函数:
class Solution {public:bool isPalindrome(string s){ int len = s.size(), i = 0, j = 0; if (len < 2) return true; string revs = s; reverse(revs.begin(), revs.end()); while(i < len && j < len) { while(i < len && !isdigit(s[i]) && !isalpha(s[i])) i++; // isalnum(); while(j < len && !isalnum(revs[j])) j++; if (toupper(s[i++]) != toupper(revs[j++])) return false; } return true;}};
不用的话就:
class Solution {public:bool isPalindrome(string s){ int len = s.size(), i = 0, j = len - 1; if (len < 2) return true; while(i < len && j >= 0) { while(i < len && !isalnum(s[i])) i++; while(j >= 0 && !isalnum(s[j])) j--; if( i < len && j >= 0 && toupper(s[i++]) != toupper(s[j--])) //注意要先判断ij是否合法 return false; } return true;}};
提交第一个时,出现了:
Congratulations, you‘ve just unlocked a solution!
之前没碰见过,不知道是不是新的功能。然后点进去是评价的界面。给评了个5分。
界面说:The idea is simple, have two pointers – one at the head while the other one at the tail. Move them towards each other until they meet while skipping non-alphanumeric> characters.
leetcode[125] Valid Palindrome
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。