zoukankan      html  css  js  c++  java
  • 判断字符串是否是回文:运用栈&reverse()

    一、运用栈

        function Stack() {
            this.dataStore = [];
            this.top = 0;//top的值等同于数组内的元素个数
            this.push = push;
            this.pop = pop;
        }
        function push(element) {
            this.dataStore[this.top++] = element;
        }
        function pop() {
            return this.dataStore[--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.top > 0) {
                rword += s.pop();//将新栈中的元素通过pop()方法翻转
            }
            if (word == rword) {
                return true;
            } else {
                return false;
            }
        }
        var word = "hello";
        if (isPalindrome(word)) {
            alert(word + " is a palindrome.");
        } else {
            alert(word + " is not a palindrome.");
        }
         word = "racecar";
        if (isPalindrome(word)) {
            alert(word + " is a palindrome.");
        } else {
            alert(word + " is not a palindrome.");
        } 

     二、间接使用数组的reverse()方法

         function isPalindrome(word) {
            var a = word.split("");//将字符串转化为数组,split()中""必不可少
            var b = a.join();//将数组转化为字符串
            var a1 = a.reverse();
            var b1 = a1.join();
            if (b == b1) {//字符串可以运用"==",数组不可以
                return true;
            } else {
                return false;
            }
        }
        var word = "hello";
        if (isPalindrome(word)) {
            alert(word + " is a palindrome.");
        } else {
            alert(word + " is not a palindrome.");
        } 
        word = "racecar";
        if (isPalindrome(word)) {
            alert(word + " is a palindrome.");
        } else {
            alert(word + " is not a palindrome.");
        } 
  • 相关阅读:
    FrameBuffer系列 之 一点资源
    FrameBuffer系列 之 显示图片
    FrameBuffer系列 之 相关结构与结构体
    FrameBuffer系列 之 介绍
    FrameBuffer系列 之 简单编程
    程序员五大层次,你属于哪一层?
    提高编程效率的14件事
    GTK简单了解记录
    __read_mostly变量含义
    [系统启动]Printk与sched_clock_init的一点分析
  • 原文地址:https://www.cnblogs.com/feile/p/5372611.html
Copyright © 2011-2022 走看看