• 125. Valid Palindrome


    Problem:

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

    Note: For the purpose of this problem, we define empty string as valid palindrome.

    Example 1:

    Input: "A man, a plan, a canal: Panama"
    Output: true
    

    Example 2:

    Input: "race a car"
    Output: false
    

    思路
    设置两个指针,分别从前往后和从后往前遍历,如果遇到非数字或字母字符就跳过,这里可以用isalnum()函数进行判断,非常方便,然后判断2个为数字或字母的字符是否相等。注意大小写也认为是相同的,所以可以用toupper()函数将小写都变为大写再进行比较。

    Solution:

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

    性能
    Runtime: 8 ms  Memory Usage: 9.5 MB

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    算法提高 身份证号码升级
    枚举排列
    排列数
    算法训练 K好数
    算法训练 前缀表达式
    算法训练 区间k大数查询
    最大最小公倍数
    Anagrams问题
    Uiautomator 2.0
    Uiautomator 2.0
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12267031.html
Copyright © 2020-2023  润新知