Bootstrap

验证回文字符串

输入: "A man, a plan, a canal: Panama"
输出:true
解释:"amanaplanacanalpanama" 是回文串



##############################------------------------------------------------------------------------------
#验证回文字符串


class Solution:
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        
        n = len(s)
        i = 0
        j = n-1

        while i < j:
            if s[i].isalnum() == False:
                i += 1
                continue
            if s[j].isalnum() == False:
                j -= 1
                continue
            if s[i].lower() != s[j].lower():
                return False
            i += 1
            j -= 1
        return True


if __name__ == '__main__':
	s = Solution()
	str =  "A man, a plan, a canal: Panama"
	print(s.isPalindrome(str))

C++的写法

注意C++的字符串大小写的转化

        transform(s.begin(), s.end(), s.begin(), ::tolower);  变小写

        transform(s.begin(), s.end(), s.begin(), ::toupper); 变大写




#include<iostream>
#include<bits/stdc++.h>

using namespace std;

class Solution {
public:
    bool isPalindrome(string s) {

        transform(s.begin(), s.end(), s.begin(), ::tolower);

        string str="";
        for(int i =0;i<s.size();i++)  {
            if(isChar(s[i])) {
                str+=s[i];
            }
        }

        if(str == string(str.rbegin(), str.rend())) {
            return true;
        }
        return false; 

    }

    bool isChar(char c) {
        return (c>='a' && c<='z') || (c>='0'&& c<='9');
    }
};

int main(int argc, char* argv[]) {
	string str = "A man, a plan, a canal: Panama";

	Solution s;
	cout<<s.isPalindrome(str)<<endl;

	return 0;
}

;