【两次过】Lintcode 415:有效回文串

给定一个字符串,判断其是否为一个回文串。只考虑字母和数字,忽略大小写。

样例

"A man, a plan, a canal: Panama" 是一个回文。

"race a car" 不是一个回文。

挑战

O(n) 时间复杂度,且不占用额外空间。

解题思路:

    先将字符串处理成只包含数字和小写字母的形式。然后设置首尾指针对撞遍历即可。

    注意大写转小写字母转换可以使用<cctype>库函数中的tolower()函数

    拓展:

    小写转大写字母:int tolower ( int c );

    是否为字母:bool isalpha ( int c );
    是否为字母或数字:bool isalnum ( int c );等等

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;
        
        for(int t = 0;t<s.size();t++)
        {
            if((s[t] >= 'a' && s[t] <= 'z') || (s[t] >= 'A' && s[t] <= 'Z'))
            {
                s[t] = tolower(s[t]);
            }
            else if(s[t] >= '0' && s[t] <= '9')
            {
                continue;
            }
            else
            {
                s.erase(t,1);
            }
        }
        
        int i = 0;
        int j = s.size()-1;
        
        while(i<j)
        {
            if(s[i] != s[j])
                return false;
            
            i++;
            j--;
        }
        
        return true;
    }
};


猜你喜欢

转载自blog.csdn.net/majichen95/article/details/80699071