Skip to content

Latest commit

 

History

History
34 lines (31 loc) · 1.31 KB

125. Valid Palindrome.md

File metadata and controls

34 lines (31 loc) · 1.31 KB

思路

题目要求判断当忽略非字母非数字字符后,给定字符串是否回文(忽略大小写)。
为了方便两个字符是否相等,可以先定义一个transformer函数将字符映射到某个数字:

  • 若是0 ~ 9的数字,则映射到数字 -1 ~ -10;
  • 若是字母,则映射到数字0 ~ 9;
  • 若是非字母非数字,全部映射到其他数如999;

然后再用两个指针low和high从两头往中间遍历并比较大小即可。
时间复杂度O(n),空间复杂度O(1)

C++

class Solution {
private:
    int transformer(char c){ // 将所有字符映射到整数以方便比较
        if('0' <= c && c <= '9') return (-1 * c - 1);
        if('a' <= c && c <= 'z') return c - 'a';
        if('A' <= c && c <= 'Z') return c - 'A';
        return 999;

    }
public:
    bool isPalindrome(string s) {
        int low = 0, high = s.size() - 1;
        while(low < high){
            while(low < high && transformer(s[low]) == 999) low++; // 跳过非字母非数字
            while(low < high && transformer(s[high]) == 999) high--;  // 跳过非字母非数字
            if(transformer(s[low++]) != transformer(s[high--])) return false;
        }
        return true;
        
    }
};