125. Valid Palindrome

1.問題

  • 判斷一個字串是否屬於回文, 只需要考慮數字及字母, 字母可忽略大小寫

2.想法

  • 提問

    • 確認題意:

  • function header, parameter

  • test input

  • 觀察

    • 保留字串中屬於字母及數字的部分, 並從兩側比對

  • 說明想法

  • 測試計算複雜度

3.程式碼

class Solution {
public:
    bool isPalindrome(string s) {
        if (s.empty()) {
            return true;
        }
        
        string s2="";
        int size = s.length();
        for (int i = 0; i < size; i++) {
            if (isalpha(s[i]) || isdigit(s[i])) {
                s2.push_back(tolower(s[i]));
            }
        }
        
        for (int i = 0; i < s2.length()/2; i++) {
            if (s2[i] != s2[s2.length() - 1 -i]) {
                return false;
            }
        }
        
        return true;
    }
};

Last updated