聲明:
作者不是什麼大佬,只是想寫寫算法,提高一下自己的內功。所以代碼可能會非常凌亂,(大佬們就當個笑話看就可以了),但我會認真註釋。
最後如果有路過的大佬,希望可以留下你們的建議和看法,謝謝!
125. 驗證迴文串
一、原題鏈接
二、題目介紹
給定一個字符串,驗證它是否是迴文串,只考慮字母和數字字符,可以忽略字母的大小寫。
說明:本題中,我們將空字符串定義爲有效的迴文串。
三、測試用例
1.示例
輸入: “A man, a plan, a canal: Panama”
輸出: true
2.示例
輸入: “race a car”
輸出: false
四、思路解析
在面對判斷迴文串的情況我一般會使用快慢指針的方式進行解答。
通過快慢指針快速定位到中點,之後從兩端出發依此判斷。
注意:這道題型簡單會有更快速的方式,但是如果固定使用快慢指針解題,該題可以當作快慢指針的入門練習題
五、代碼
class Solution {
public boolean isPalindrome(String s) {
// 將字符串刷新到自定義鏈表
int cha = 32;
LinkedChar linkedChar = new LinkedChar();
for (char c : s.toCharArray()) {
if (c >= '0' && c <= '9' || c >= 'a' && c <= 'z') {
linkedChar.push(c);
} else if (c >= 'A' && c <= 'Z') {
int temp = c + 32;
linkedChar.push((char) temp);
}
}
// 判斷簡單的情況,直接返回
switch (linkedChar.size){
case 0: return true;
case 1: return true;
case 2: return linkedChar.head.value == linkedChar.head.next.value;
case 3: return linkedChar.head.value == linkedChar.head.next.next.value;
}
// 根據快慢指針獲取中間元素
LinkedElem fast = linkedChar.head;
LinkedElem slow = linkedChar.head;
while (fast.next!=null && fast.next.next !=null) {
slow = slow.next;
fast = fast.next.next;
}
// 根據最後一次指針停留位置和鏈表長度,設置快慢指針的往左右遍歷的位置
if(linkedChar.size%2==0){
fast = slow.next;
}else {
fast = slow.next;
slow = slow.pre;
}
// 開始遍歷
while (fast!=null){
if(fast.value != slow.value){
// 有一次不一樣就返回false
return false;
}else {
fast = fast.next;
slow = slow.pre;
}
}
// 全部通過返回true
return true;
}
}
// 自定義Char類型的鏈表結構
class LinkedChar {
// 當前鏈表頭指針
LinkedElem head;
// 當前鏈表尾指針
LinkedElem last;
// 當前鏈表長度
int size = 0;
// 鏈表是否爲空
boolean isEmpty() {
return size == 0;
}
// 鏈表添加
void push(char c) {
// 將要添加的字符封裝爲鏈表元素
LinkedElem elem = new LinkedElem();
elem.value = c;
// 分情況添加 此時爲空時添加元素
if (size == 0) {
// 更新鏈表的頭尾指針
this.head = elem;
this.last = elem;
elem.next = null;
elem.pre = null;
} else {
// 設定當前元素的前一個元素爲尾部
elem.pre = this.last;
// 將當前元素放到尾部
this.last.next = elem;
// 跟新尾部的指針
this.last = elem;
}
// 長度加1
size++;
}
}
// 鏈表元素
class LinkedElem {
// 前指針
LinkedElem pre;
// 後指針
LinkedElem next;
// 當前元素
char value;
}