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方法。

         注意空串的处理

  • 相关阅读:
    DOM对象
    多态
    封装和继承
    析构函数
    构造函数
    二维数组
    javascript的基本语法
    javascript数组
    js
    BOM和DOM的区别
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4394351.html
Copyright © 2011-2022 走看看