zoukankan      html  css  js  c++  java
  • Valid Palindrome

    Valid Palindrome

    问题:

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

    思路:

      简单的数学推导

    我的代码:

    public class Solution {
        public boolean isPalindrome(String s) {
            if(s == null || s.length() == 0)  return true;
            int left = 0;
            int right = s.length() - 1;
            while(left < right)
            {
                while(!isAlpha(s.charAt(left)) && left < right) left++;
                while(!isAlpha(s.charAt(right)) && left < right) right--;
                if(!isEqual(s.charAt(left), s.charAt(right))) return false;
                left ++;
                right --;
            }
            return true;
        }
        public boolean isAlpha(char c)
        {
            return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'));
        }
        public boolean isEqual(char left, char right)
        {
           return (left == right || Math.abs(left-right) == 32);
        }
    }
    View Code

    他人代码:

    public class Solution {
        public boolean isPalindrome(String s) {
            if (s == null || s.length() == 0) {
                return true;
            }
    
            int front = 0;
            int end = s.length() - 1;
            while (front < end) {
                while (front < s.length() && !isvalid(s.charAt(front))){ // nead to check range of a/b
                    front++;
                }
    
                if (front == s.length()) { // for emtpy string “.,,,”     
                    return true; 
                }           
    
                while (end >= 0 && ! isvalid(s.charAt(end))) { // same here, need to check border of a,b
                    end--;
                }
    
                if (Character.toLowerCase(s.charAt(front)) != Character.toLowerCase(s.charAt(end))) {
                    break;
                } else {
                    front++;
                    end--;
                }
            }
    
            return end <= front; 
        }
    
        private boolean isvalid (char c) {
            return Character.isLetter(c) || Character.isDigit(c);
        }
    }
    View Code

    学习之处:

    • Character.isLetter(c) Character.isDigit(c) Character.toLowerCase(c)  Character还有这几个API不错
    • 写代码的时候,尽量的简洁和功能划分,比如我的代码里面的isAlpha和isEqual都可以用一行代码解决,这样就不要用多行,注意功能划分。 
  • 相关阅读:
    浅谈if __name__='__main__'
    python打开文件方式
    关于ValueError: not enough values to unpack (expected 4, got 1)
    一篇文章让你搞懂this
    Cannot read property 'addEventListener' of null报错的解决办法
    看JS操作符中二进制补码
    js的原型和原型链理解
    你不知道的js中对象,数组互相转换
    浅谈js中a+++a与a+a++值区别
    Integer跟int的区别
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4337446.html
Copyright © 2011-2022 走看看