JS使用棧判斷給定字符串是否是回文算法示例
本文實例講述了JS使用棧判斷給定字符串是否是回文算法。分享給大家供大家參考,具體如下:
/*使用棧stack類的實現(xiàn)*/
function stack() {
this.dataStore = [];//保存棧內(nèi)元素,初始化為一個空數(shù)組
this.top = 0;//棧頂位置,初始化為0
this.push = push;//入棧
this.pop = pop;//出棧
this.peek = peek;//查看棧頂元素
this.clear = clear;//清空棧
this.length = length;//棧內(nèi)存放元素的個數(shù)
}
function push(element){
this.dataStore[this.top++] = element;
}
function pop(){
return this.dataStore[--this.top];
}
function peek(){
return this.dataStore[this.top-1];
}
function clear(){
this.top = 0;
}
function length(){
return this.top;
}
/*使用棧判斷給定字符串是否是回文的算法*/
function isPalindrome(word){
var s = new stack();
for(var i = 0;i < word.length;i++){
s.push(word[i]);
}
var rword = "";
while(s.length() > 0){
rword += s.pop();
}
if(word == rword){
return true;
}else{
return false;
}
}
var word1 = "racecar";
if(isPalindrome(word1)){
console.log(word1 + " is a palindrome")//racecar is a palindrome
}
這里使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼,可得如下運行結(jié)果:

更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript數(shù)學運算用法總結(jié)》、《JavaScript排序算法總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》、《JavaScript查找算法技巧總結(jié)》及《JavaScript錯誤與調(diào)試技巧總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計有所幫助。
相關(guān)文章
Javascript怎樣使用SessionStorage和LocalStorage
這篇文章主要介紹了Javascript怎樣使用SessionStorage和LocalStorage,對web存儲數(shù)據(jù)感興趣的同學,可以參考下2021-04-04
JS getAttribute和setAttribute(取得和設(shè)置屬性)的使用介紹
本篇文章是對JS中的getAttribute和setAttribute(取得和設(shè)置屬性)的使用進行了詳細的分析介紹,需要的朋友可以參考下2013-07-07
詳解JavaScript中的before-after-hook鉤子函數(shù)
最近看別人的代碼,接觸到一個插件,before-after-hook,百度搜一圈也沒有看到什么地方有教程,本文就來簡單介紹一下這個插件的使用方法,需要的可以參考一下2022-12-12

