LintCode 415 Valid Palindrome

題目:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Notice
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.

思路:
這題可以從左右指針來看,頭一個,尾一個,一路往中心走,走的同時要判斷是不是正確字元,可以用 isalnum 來解決,因為考慮大小寫,所以在比較的時候要使用 toupper (tolower 也行),全部統一轉換成一種大小寫來比較即可,只要一出錯就 return false.

程式:

class Solution {
public:
    /**
     * @param s: A string
     * @return: Whether the string is a valid palindrome
     */
    bool isPalindrome(string &s) {
        // write your code here
        if (s.empty())
            return true;
        
        int l = 0;
        int r = s.size()-1;
        
        while( l < r ) {
            while(!isalnum(s[l]) && l < r)
                l++;
            while(!isalnum(s[r]) && l < r)
                r--;
            if (toupper(s[l]) != toupper(s[r]))
                return false;
            l++;
            r--;
        }
        return true;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容