zoukankan      html  css  js  c++  java
  • 【LeetCode】125

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

    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.

    Tags :Two Pointers String

    Solution 1 : my weak suolution, create a new string to input only alphanumeric
    bool isPalindrome(string s) {    
        if(s.empty())return true;
        string::iterator iter1=s.begin(),iter2=s.end();
        string news;
        for(;iter1!=iter2;iter1++){
            if(isalnum(*iter1))
                news.push_back(tolower(*iter1));
        }
        if(news.size()==1)return true;
        for(int i=0,j=news.size()-1;i<j;i++,j--){
            if(news[i]!=news[j])return false;
        }
        return true;
    }

    Solution 2: clean code

        bool isPalindrome(string s) {
            for (int i = 0, j = s.size() - 1; i < j; i++, j--) { // Move 2 pointers from each end until they collide
                while (isalnum(s[i]) == false && i < j) i++; // Increment left pointer if not alphanumeric
                while (isalnum(s[j]) == false && i < j) j--; // Decrement right pointer if no alphanumeric
                if (toupper(s[i]) != toupper(s[j])) return false; // Exit and return error if not match
            }
        
            return true;
        }
     
  • 相关阅读:
    使用Webuploader大文件分片传输
    php面向对象的封装性
    前端实习经历
    Js_protoType_原型
    SVN客户端与服务器端搭建操作
    安装PL/SQL客户端来访问操作步骤
    安装Oracle数据库操作步骤
    MyEclipse2014安装操作步骤+破解
    模块学习笔记
    json与导入模块目录
  • 原文地址:https://www.cnblogs.com/irun/p/4799081.html
Copyright © 2011-2022 走看看