Create 125. Valid Palindrome.md

This commit is contained in:
唐树森 2018-10-03 22:24:17 +08:00 committed by GitHub
parent f3fddaeb8b
commit 38e74de772
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

34
125. Valid Palindrome.md Normal file
View File

@ -0,0 +1,34 @@
# [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;
}
};
```