zoukankan      html  css  js  c++  java
  • Valid Palindrome

    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.

    public class Solution {
        public boolean isPalindrome(String s) {
            if(s=="")return true; 
            s=s.toLowerCase();
            int len=s.length();
            int begin=0,end=len-1;
            while(begin<end){
                while(!valid(s.charAt(begin))){
                    ++begin;
                    if(begin>=end) return true;
                }
                while(!valid(s.charAt(end))){
                    --end;
                    if(begin>=end) return true;
                }
                if(s.charAt(begin)==s.charAt(end)){
                    begin++;
                    end--;
                }else return false;            
            }
            return true;
            
        }
        Boolean valid(char c){
            if(c>='0'&&c<='9')return true;
            if(c>='a'&&c<='z')return true;
            return false;
        }
    }

    注意:java遍历字符串使用charAt方法。此代码使用了库函数toLowerCase方法。

         注意空串的处理

  • 相关阅读:
    纪伯伦:我曾七次鄙视我的灵魂
    字典和集合
    元组
    列表
    字符串
    数值类型
    内置函数了解一下
    了解Python
    centos7安装mysql数据库
    xenserver 上传centos6.8镜像
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4394351.html
Copyright © 2011-2022 走看看