leetcode 125. Valid Palindrome ----- java

來源:互聯網
上載者:User

標籤:字串   java   迴文   rpo   lower   rar   man   car   class   

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;                    }}

 

leetcode 125. Valid Palindrome ----- java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.