当前位置: 代码迷 >> 综合 >> 使用栈判断回文
  详细解决方案

使用栈判断回文

热度:62   发布时间:2023-10-10 20:48:51.0

Stack.js

function Stack() {this.dataStore=[];this.push=function (element) {this.dataStore[this.dataStore.length]=element;}this.pop=function(){if(this.dataStore.length<1)return null;//取得最后的数据var buffer = this.dataStore[this.dataStore.length-1];//把最后的数据置空this.dataStore[this.dataStore.length-1]=null;//改变数组的长度this.dataStore.length--;//返回数据return buffer;}this.peek=function () {//取得头部数据var buffer = this.dataStore[0];//获得数组的长度var length = this.dataStore.length;//遍历数据for(var i=0;i<length-1;i++){//把数据往前面移动this.dataStore[i]=this.dataStore[i+1];}//把最后的数据置空this.dataStore[length-1]=null;//数组的长度减少this.dataStore.length--;//返回数据return buffer;}this.length = function () {return this.dataStore.length;}this.clear=function () {delete this.dataStore;this.dataStore=[];}this.forEach=function (call) {//1,获得数组的长度var length = this.dataStore.length;//2,遍历数据for(var i=length-1;i>=0;i--){// var item= this.dataStore[i];call(this.dataStore[i]);}}}

 

HTML

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><script src="Stack.js"></script>
</head>
<body></body>
<script>String.prototype.forEach = function (call) {for(var i=0;i<this.length;i++) {call(this[i]);}}function isPalindrome(data) {var stack = new Stack();data.forEach(function (item) {stack.push(item);});var buffer = '';stack.forEach(function (word) {buffer = buffer+word});if(buffer==data)return true;elsereturn false;}console.log(isPalindrome("aabbaa"));
</script>
</html>

 

  相关解决方案