LeetCode(125)--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.

解題思路:
求迴文的題目無論是在研究生入學考試,還是在面試中時有出現。本題是忽略空格、字符、大小寫的約束,來判斷一句話的內容是否是迴文。通過對字符串從兩端進行掃描,如果有字母就進行比較,如果不是將該字符忽略找到下一個字符。本題的思路使我們聯想起折半查找方法。

提交的代碼:

public boolean isPalindrome(String s) {
       if(s == null || s.length() == 0) 
            return true;
        int i = 0;
        int j = s.length() - 1;
        while(i < j) {
            while(i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;
            while(i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;
            if(Character.toLowerCase(s.charAt(i++)) == Character.toLowerCase(s.charAt(j--))){
                continue;
            }else{
                return false;
            }
        }
        return true;
    }

該方法的時間複雜度是O(N),在線性的時間內完成了迴文的搜索。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章