zoukankan      html  css  js  c++  java
  • leetcode[125] Valid Palindrome

    判断一个字符串是不是回文,忽略其中的非数字和非字母,例如符号和空格不考虑。

    For example,
    "A man, a plan, a canal: Panama" is a palindrome.
    "race a car" is not a palindrome.

    Note:
    Have you consider that the string might be empty? This is a good question to ask during an interview.

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

    想到用reverse函数:

    class Solution {
    public:
    bool isPalindrome(string s)
    {
        int len = s.size(), i = 0, j = 0;
        if (len < 2) return true;
        string revs = s;
        reverse(revs.begin(), revs.end());
        while(i < len && j < len)
        {
            while(i < len && !isdigit(s[i]) && !isalpha(s[i])) i++; // isalnum();
            while(j < len && !isalnum(revs[j])) j++;
            if (toupper(s[i++]) != toupper(revs[j++]))
                return false;
        }
        return true;
    }
    };

    不用的话就:

    class Solution {
    public:
    bool isPalindrome(string s)
    {
        int len = s.size(), i = 0, j = len - 1;
        if (len < 2) return true;
        while(i < len && j >= 0)
        {
            while(i < len && !isalnum(s[i])) i++;
            while(j >= 0 && !isalnum(s[j])) j--;
            if( i < len && j >= 0 && toupper(s[i++]) != toupper(s[j--])) //注意要先判断ij是否合法
                return false;
        }
        return true;
    }
    };

    提交第一个时,出现了:

    Congratulations, you've just unlocked a solution! 

    之前没碰见过,不知道是不是新的功能。然后点进去是评价的界面。给评了个5分。

    界面说:The idea is simple, have two pointers – one at the head while the other one at the tail. Move them towards each other until they meet while skipping non-alphanumeric> characters.

  • 相关阅读:
    php 处理并发问题
    phpstudy 版本切换注意的问题
    php读取文件内容的三种方法
    防止重复提交表单的两种方法
    php 压缩函数gzencode gzdeflate gzcompress
    回调函数解析
    回调函数
    如何卸载红蜘蛛
    无法启动此程序,因为计算机中丢失MSVCR110.dll的解决方法
    mysql 去除重复 Select中DISTINCT关键字的用法
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4141781.html
Copyright © 2011-2022 走看看