標籤:
1、題目名稱
Valid Palindrome(迴文字串)
2、題目地址
https://leetcode.com/problems/valid-palindrome/
3、題目內容
英文:Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
中文:給出一個字串,只考慮字母和數字,判斷該字串是否為迴文字串
例如:
"A man, a plan, a canal: Panama" 是一個迴文字串
"race a car" 不是一個迴文字串
4、題目分析
如果要判斷一個字串是否是迴文字串,可以兩個變數,從兩側開始比較有效字元是否相等。這裡有效字元是指 ‘a‘-‘z‘、‘A‘-‘Z‘、‘0‘-‘9‘ 這三個區間內的字元。
5、解題方法1
可以將字串中有效字元,寫入一個鏈表,再將鏈錶轉化為數組,直接判斷數組兩側對稱位置的字元是否匹配。
實現的Java代碼如下:
import java.util.LinkedList;/** * 功能說明:LeetCode 125 - Valid Palindrome * 開發人員:Tsybius2014 * 開發時間:2015年8月4日 */public class Solution { /** * 檢測一個字串是否是迴文(忽略大小寫,只考慮英文和數字) * @param s 被檢測字串 * @return */ public boolean isPalindrome(String s) { if (s == null) { return false; } if (s.trim().isEmpty()) { return true; } //將有效字元選出並存入鏈表 LinkedList<Character> linkedList = new LinkedList<Character>(); for (char ch : s.toCharArray()) { if ((ch >= ‘a‘ && ch <= ‘z‘) || (ch >= ‘0‘ && ch <= ‘9‘)) { linkedList.add(ch); } else if (ch >= ‘A‘ && ch <= ‘Z‘) { linkedList.add((char)(ch + ‘a‘ - ‘A‘)); } } if (linkedList.size() <= 1) { return true; } //將鏈錶轉換為數組比較 Object[] array = linkedList.toArray(); for (int i = 0; i <= array.length / 2; i++) { if (!array[i].equals(array[array.length - 1 - i])) { return false; } } return true; }}
6、解題方法2
選擇兩個數字i和j,直接從字串的首和尾開始迴圈,直到i>=j為止。如果出現兩側對應字元不匹配的情況,則直接判定此字串不是迴文字串。全部字元考察完畢後,如果未發現對應位置字元不匹配的情況,則認為此字串是迴文字串。
實現的Java代碼如下:
import java.util.LinkedList;/** * 功能說明:LeetCode 125 - Valid Palindrome * 開發人員:Tsybius2014 * 開發時間:2015年8月4日 */public class Solution { /** * 檢測一個字串是否是迴文(忽略大小寫,只考慮英文和數字) * @param s 被檢測字串 * @return */ public boolean isPalindrome(String s) { if (s == null) { return false; } if (s.trim().isEmpty()) { return true; } int i = 0; int j = s.length() - 1; int chLeft; //左側字元 int chRight; //右側字元 while (i < j) { chLeft = s.charAt(i); chRight = s.charAt(j); //既非英文也非數位字元直接忽略 if (!(chLeft >= ‘A‘ && chLeft <= ‘Z‘) && !(chLeft >= ‘a‘ && chLeft <= ‘z‘) && !(chLeft >= ‘0‘ && chLeft <= ‘9‘)) { i++; continue; } if (!(chRight >= ‘A‘ && chRight <= ‘Z‘) && !(chRight >= ‘a‘ && chRight <= ‘z‘) && !(chRight >= ‘0‘ && chRight <= ‘9‘)) { j--; continue; } //大寫英文字母轉成小寫 if (chLeft >= ‘A‘ && chLeft <= ‘Z‘) { chLeft = chLeft + ‘a‘ - ‘A‘; } if (chRight >= ‘A‘ && chRight <= ‘Z‘) { chRight = chRight + ‘a‘ - ‘A‘; } //比較字元 if (chLeft != chRight) { return false; } else { i++; j--; } } return true; }}
END
LeetCode:Valid Palindrome