[LeetCode] 125. Valid Palindrome

题目链接:传送门

Description

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.

Solution

题意:

给定一个串,问串中的字母数字字符组成的新串是否为回文串(忽略大小写)

思路:

先处理字母数字,再判回文

class Solution {
public:
    string transfer(string s) {
        string res = "";
        for (int i = 0; i < s.length(); i++) {
            if (isalpha(s[i])) {
                res += tolower(s[i]);
            } else if (isdigit(s[i])) {
                res += s[i];
            }
        }
        return res;
    }
    bool isPalindrome(string s) {
        string res = transfer(s);
        int len = res.length();
        for (int i = 0; i < len; i++) {
            if (res[i] != res[len - 1 - i])  return false;
        }
        return true;
    }
};
posted @ 2018-03-05 01:19  酒晓语令  阅读(100)  评论(0编辑  收藏  举报