使用棧判斷給定字符串是否是回文的算法


使用棧判斷給定字符串是否是回文的算法

/*使用棧stack類的實現*/
function stack() {
    this.dataStore = [];//保存棧內元素,初始化為一個空數組
    this.top = 0;//棧頂位置,初始化為0
    this.push = push;//入棧
    this.pop = pop;//出棧
    this.peek = peek;//查看棧頂元素
    this.clear = clear;//清空棧
    this.length = length;//棧內存放元素的個數
}

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
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM