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.

  • 相关阅读:
    runtime 01-类与对象
    iOS 远程推送的实现
    iOS 选取上传图片界面
    NSAssert
    TableView下拉cell
    此博客主人已搬家访问新家地址:http://write.blog.csdn.net/postlist
    教你如何快速集成第3方
    iPhone应用开发 UITableView学习点滴详解
    苹果Xcode 证书生成、设置、应用完整图文教程
    NSXMLParser解析xml格式
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4141781.html
Copyright © 2011-2022 走看看