[LeetCode][Java] Valid Palindrome

來源:互聯網
上載者:User

標籤:leetcode   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.

題意:

給定一個字串,判定它是否是迴文串,只考慮數字和字母字元,忽略其他字元。

比如,

"A man, a plan, a canal: Panama"是一個迴文串。

"race a car"不是迴文串。

注意:

你想到了字串可能為空白的情況了嗎?面試的時候可能會問到哦

在本題中,我們定義Null 字元為迴文串。

演算法分析:

首先將給定的字串中數字和字母重新加入新的數組中,忽略其他的字元,之後統一大小寫。重新按照迴文串的規則判斷新的字串數組。

思路比較簡單,直接上代碼了。

AC代碼:

<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution {    public  boolean isPalindrome(String s)     {    boolean flag=true;int i;ArrayList<Character> list=new ArrayList<Character>();s=s.toUpperCase();//所有的小寫字元統一變換為大寫字元    if(s==null||s.length()==0) return true;    for(i=0;i<s.length();i++)    {    if((s.charAt(i)>='A'&&s.charAt(i)<='Z')||(s.charAt(i)>='0'&&s.charAt(i)<='9'))    {    list.add(s.charAt(i));    }    }    for(i=0;i<list.size();i++)    {    if(list.get(i)==list.get(list.size()-i-1))    flag=true;    else    {    flag=false;    break;    }    }    return flag;       }}</span>

著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Valid Palindrome

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.