首页 > 代码库 > [leetcode] 1. Valid Palindrome
[leetcode] 1. Valid Palindrome
leetcode的第一题,回文数判断。
原题如下:
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.
回文数是个很基础的东西,这里给了两个example作为提示:给的样本中可能会有空格,标点和特殊符号等,要考虑一下先判断string是否是纯string再去进行回文判断。
leetcode给的答案是伪代码,也解释的很清楚:
public boolean isPalindrome(String s) { int i = 0, j = s.length() - 1; while (i < j) { while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++; while (i < j && !Character.isLetterOrDigit(s.charAt(j))) j--; if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) { return false; } i++; j--; } return true;}
思路结束,具体在操作的时候就是C++的能力本身了。随手写的代码(日后改)[2014-11-09]:
#include <string>#include <algorithm>bool isPalindrome(string s) { if (s.empty()) { return false; } string tmp = ""; for (int i = 0; i < s.size(); i++) { if (isalnum(s.at(i))) { tmp += s[i]; } } transform(tmp.begin(), tmp.end(), tmp.begin(), ::toupper); for (int i = 0; i < tmp.size() / 2; i++) { if (tmp.at(i) != tmp.at(tmp.size() - 1 - i)) { return false; } } return true;}
C++水平还不够,但是过了。回文的问题以后再补充。
[leetcode] 1. Valid Palindrome
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。