zoukankan      html  css  js  c++  java
  • 使用栈判断给定字符串是否是回文的算法

    使用栈判断给定字符串是否是回文的算法

    /*使用栈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
    }
  • 相关阅读:
    js 和 jquery的宽高
    client、offset、scroll
    web开发中会话跟踪的方法有哪些
    前端需要注意哪些SEO
    ES6 Set和Map数据结构
    ES6实现数组去重
    ES6 Symbol
    ES6对象的拓展
    ES6数组的拓展
    ES6函数的拓展
  • 原文地址:https://www.cnblogs.com/baiyangyuanzi/p/6673644.html
Copyright © 2011-2022 走看看