LeetCodeOJ. Valid Palindrome

試題請參見: 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, 因爲需要考慮的情況太多了.

於是爲了使代碼看起來比較簡潔, 於是先使用一個函數過濾無用的字符串, 再進行比對.

遇到的問題

各種Runtime Error. 
尤其是當過濾之後字符串長度爲0時.

源代碼

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;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章