試題請參見: https://oj.leetcode.com/problems/valid-palindrome/
題目概述
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
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.
解題思路
一開始總想着不佔用額外的內存空間解決問題, 但是運行時各種Runtime Error, 因爲需要考慮的情況太多了.於是爲了使代碼看起來比較簡潔, 於是先使用一個函數過濾無用的字符串, 再進行比對.
遇到的問題
源代碼
class Solution {
public:
bool isPalindrome(std::string s) {
s = filter(s);
for ( size_t i = 0; s.size() != 0 && i <= s.size() / 2; ++ i ) {
if ( s.at(i) != s.at(s.size() - i - 1) ) {
return false;
}
}
return true;
}
private:
std::string filter(std::string s) {
std::string d;
for ( size_t i = 0; i < s.size(); ++ i ) {
if(::isalpha(s[i]) || ::isdigit(s[i])){
d.push_back(::tolower(s[i]));
}
}
return d;
}
};