面試題:判斷字符串是否回文


題干:

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.

備注:面試者可以會問這樣的問題:
  問:空字符串算是回文字符串嗎?
  答:在這個問題里,我們將空字符串運定義為回文字符串。


分析:

palindrome  ['pælɪndrəʊm]  n.回文(即正讀反讀都一樣的詞或短語)

step1:定義兩個“指針”i,j——一個為“頭指針”,另一個是“尾指針”。

step2:兩“指針”相向移動,跳過既非字母也非數字的字符,判斷指針位置的字符是否相等。

    不相等,返回false。相等繼續移動,直到 i>=j ,返回ture。

跳過既非字母也非數字的字符,用到了 Character.isLetterOrDigit() 方法。

不區分大小寫,所以都轉化為小寫來判斷是否相等,用到了 Character.toLowerCase() 方法。

 


Solution:

 1 class Solution {
 2     public boolean isPalindrome(String s) {
 3         int i = 0, j = s.length() - 1;
 4         while (i < j) {
 5             while (i < j && !Character.isLetterOrDigit(s.charAt(i)))
 6                 i++;
 7             while (i < j && !Character.isLetterOrDigit(s.charAt(j)))
 8                 j--;
 9             if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) {
10                 return false;
11             }
12             i++;
13             j--;
14         }
15         return true;
16     }
17 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM