oj125. 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"不是迴文。

注意:
你認爲字符串可能是空的嗎?在採訪中這是一個很好的問題。

爲了這個問題的目的,我們將空字符串定義爲有效的迴文。

思路:去除字符串中的標點符號,字母都轉爲小寫,變成char數組再判斷。主要是正則表達式的使用。

public boolean isPalindrome(String s) {
        String s1 = s.replaceAll("[\\p{Punct}\\p{Z}]+","").toLowerCase();//正則表達式\\p{P}匹配標點字符,\\p{Z}匹配分隔符
        char[] s2ca = s1.toCharArray();
        int len = s2ca.length;
        int len_half = len/2;
        for(int i =0;i<len_half;i++){
            if(s2ca[i] != s2ca[len-1]) return false;
            len--;
        }
        return true;
    }




發佈了38 篇原創文章 · 獲贊 7 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章