【leetcode】3.1 valid palindrome

来源:互联网 发布:网狐6603手机捕鱼源码 编辑:程序博客网 时间:2024/06/07 01:15

【问题描述】

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.
【自我描述】
其实就是一个字符串判断是不是所有的字符是对称的
【代码】

#include<iostream>#include <cctype>#include <algorithm>using namespace std;bool isPalindrome(string s){    if (s.length() < 2) return true;    /*    C++的Standard Library并没有提供将std::string转成大写和小写的功能,    只有在提供将char转成大写(toupper)和小写(tolower)的功能而已。    利用STL的transform配合toupper/tolower,完成std::string转换大(小)写的功能    一个transform函数,可以适用于任何类型    #include <string>    #include <cctype>    #include <algorithm>    string s = "Clare";    // toUpper    transform(s.begin(), s.end(), s.begin(), ::toupper);    // toLower    //transform(s.begin(),s.end(),s.begin(), ::tolower);    */    transform(s.begin(), s.end(), s.begin(), ::tolower);    auto char *left = s.begin();    auto char *right = s.end()-1;//Get iterator to previous element    while(left < right){        if (!::isalnum(*left))  ++left;        else if(!::isalnum(*right)) right--;        else if(*left != *right)    return false;        else{left++;    right--;}    }    return true;}void main(){    string s = "A man, a plan, a canal: Panama";    if(::isPalindrome(s))        cout << "This is a valid palindrome.\n" << endl;    else        cout << "I'm sorry.\n" << endl;}
0 0
原创粉丝点击