LeetCode-Valid Palindrome
阿新 • • 發佈:2018-12-12
Description: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car" Output: false
題意:判斷一個字串是否是迴文,忽略除字母外的其他字元,並且對大小寫不敏感;
解法:可以從字串的首尾處開始向中間遍歷,找到出現的字母或者數字,判斷兩個字元是否相等;
Java
class Solution { public boolean isPalindrome(String s) { int st = 0; int ed = s.length() - 1; s = s.toLowerCase(); while (st < ed) { while (st < s.length() && !Character.isLetterOrDigit(s.charAt(st))) st++; while (ed >= 0 && !Character.isLetterOrDigit(s.charAt(ed))) ed--; if (st >= ed) break; if (s.charAt(st) != s.charAt(ed)) return false; st++; ed--; } return true; } }