玩命加载中 . . .

125/680-验证回文串


LeetCode 125. Valid Palindrome

LeetCode-125

Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Example 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

method: 双指针

isalnum()判断字符是不是字母或数字
isalpha()判断是不是字母
isdigit()判断是不是数字
isspace()判断是不是空格
tolower()转化为小写字母
toupper()转化为大写字母

分别从两边找符合条件的字母或数字

// 判断是不是字母或数字,可以用isalnum()代替
bool isValue(char c) {
    if (isdigit(c) || isalpha(c))
        return true;
    return false;
}

bool isPalindrome(string s) {
    int i = 0, j = s.size() - 1;
    while (i < j) {
        while (i < j && !isValue(s[i])) i++;
        while (i < j && !isValue(s[j])) j--;
        if (tolower(s[i]) != tolower(s[j])) return false;
        ++i;
        --j;
    }
    return true;
}

LeetCode 680. Valid Palindrome II

LeetCode-680

Given a string s, return true if the s can be palindrome after deleting at most one character from it.

Example 1:

Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.

method: 双指针

遇到不相等的地方,就考虑删掉一个的情况,如果删掉还不行,那就不行了

可以删掉i后面的,或者j前面的

bool isPalindrome(string s, int i, int j) {
    while (i < j) {
        if (s[i] != s[j]) return false;
        i++;
        j--;
    }
    return true;
}

bool validPalindrome(string s) {
    for (int i = 0, j = s.size() - 1; i < j; ++i, --j) {
        if (s[i] != s[j]) {
            return isPalindrome(s, i, j - 1) || isPalindrome(s, i + 1, j);
            // 删掉i后面的或j前面的
        }
    }
    return true;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录