LeetCode/solutions/125. Valid Palindrome.md

35 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [125. Valid Palindrome](https://leetcode.com/problems/valid-palindrome/description/)
# 思路
题目要求判断当忽略非字母非数字字符后,给定字符串是否回文(忽略大小写)。
为了方便两个字符是否相等可以先定义一个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;
}
};
```