zoukankan      html  css  js  c++  java
  • leetcode 125. Valid Palindrome ----- java

    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.

    判读一个字符串是否是回文字符串(只判断期中的字符和数字)。

    1、两个栈,从前向后和从后向前,然后判断两个栈是否相同。

    public class Solution {
        public boolean isPalindrome(String s) {
            Stack stack1 = new Stack<Character>();
            Stack stack2 = new Stack<Character>();
            s = s.toLowerCase();
            char[] word = s.toCharArray();
            int len = s.length();
            for( int i = 0;i<len;i++){
                if( (word[i] >= '0' && word[i] <= '9') || (word[i]>='a' && word[i]<='z')  )
                    stack1.push(word[i]);
                if( (word[len-1-i] >= '0' && word[len-1-i] <= '9') || (word[len-1-i]>='a' && word[len-1-i]<='z')  )
                    stack2.push(word[len-1-i]);
            }
    
    
            return stack1.equals(stack2);
            
        }
    }

    2、直接用两个指针记录left和right即可。

    public class Solution {
        public boolean isPalindrome(String s) {
            
            char[] word = s.toLowerCase().toCharArray();
            int len = s.length();
            int left = 0,right = len-1;
            while( left < right ){
    
                if( !((word[left] >= '0' && word[left] <= '9') || (word[left]>='a' && word[left]<='z' )) )
                    left++;
                else if( !((word[right] >= '0' && word[right] <= '9') || (word[right]>='a' && word[right]<='z' )) )
                    right--;
                else if( word[left] == word[right]){
                    left++;
                    right--;
                }else
                    return false;
            }
            return true;
    
            
            
        }
    }
  • 相关阅读:
    echars柱状图修改每条柱的颜色
    vue打开到新页面,并传递参数
    彻底了解websocket原理
    bind和on的区别
    Vue如何更新子组件
    Vue父子组件生命过程
    使用css3实现动画来开启GPU加速
    前端技术体系
    Vue中的~(静态资源处理)
    垂直居中的办法小结
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6033213.html
Copyright © 2011-2022 走看看