JavaScript 使用雙端佇列寫出迴文檢查器
阿新 • • 發佈:2021-01-09
技術標籤:前端佇列字串javascriptjs
什麼是迴文
迴文是正反都能讀通的單詞,片語,數或一些列字元的序列,例如 madam 與 racecar。
如何實現迴文檢查其的功能
如上所述,迴文是一些正反顛倒都能和之前的值一樣的序列。那麼我們只需要抽出第一位與最後一位,第二位與倒數第二位來對比即可。
class Deque {
constructor() {
this.count = 0;
this.lowestCount = 0;
this.items = {};
}
size() { return this .count - this.lowestCount; }
addFront(element) {
if ( this.isEmpty() ) this.addBack(element);
else if ( this.lowestCount > 0 ) {
this.lowestCount--;
this.items[this.lowestCount] = element;
} else {
for ( let i = this.count; i > 0; i-- ) this.items[i] = this.items[i - 1];
this.count++;
this.lowestCount = 0;
this.items[0] = element;
}
}
addBack(element) {
this.items[this.count] = element;
this.count++;
}
removeFront() {
if ( this.isEmpty() ) return undefined;
const result = this.items[this.lowestCount];
delete this.items[this.lowestCount];
this.lowestCount++;
return result;
}
removeBack() {
if ( this.isEmpty() ) return undefined;
this.count--;
const result = this.items[this.count];
delete this.items[this.count];
return result;
}
}
/**
* 驗證該序列是否為迴文
* @param {String} palindrome
*/
const PalindromeChecker = palindrome => {
if ( palindrome === undefined || palindrome === null || palindrome !== null && palindrome.length === 0 )
return false;// 判定扔進來的字元(序列)是否為 null,undefined,以及空字串
const deque = new Deque();// 例項化一個雙端佇列類
const stringArr = palindrome.toLocaleLowerCase().split(" ").join("");// 將字串重新整理(無空格)
let isEqual = true,// 判定是否為迴文的關鍵值
firstChar , lastChar;
for ( let i = 0; i < stringArr.length; i++ )
deque.addBack(stringArr.charAt(i));// 將字串傳遞給雙端佇列類
while (deque.size() > 1 && isEqual) {// 迴圈判斷
firstChar = deque.removeFront();
lastChar = deque.removeBack();
if ( firstChar !== lastChar ) isEqual = false;
}
return isEqual;
}