function Stack(){
this.dataStore = [];
this.top = 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;
}
//一、数字n转换为以b(2-9)为基数的数字
// 1.最高位为n%b,压入栈
// 2.使用n/b代替n
// 3.重复1.2.,直到n等于0,且没有余数
// 4.持续将栈内元素弹出,直到栈为空,元素依次排列,得到转换后数字的字符串形式
function mulBase(num,base){
var s = new Stack();
do{
s.push(num%base);
num = Math.floor(num /= base);
}while(num>0);
var converted = '';
while(s.length()>0){
converted += s.pop();
}
return converted;
}
var num = 32;
var base = 2;
var newNum = mulBase(num,base);
console.log(newNum)
// 二.回文 1001 racecar
function isPalindrome(word){
var a = new Stack();
for(var i = 0;i<word.length;i++){
a.push(word[i]);
}
var rword = '';
while(a.length()>0){
rword += a.pop();
}
if(word ==rword){
return true;
}
else{
return false;
}
}
var word = 'hello';
if(isPalindrome(word)){
console.log(word + ' is a palindrome');
}else{
console.log(word + ' is not a palindrome');
}
word = 'racecar';
if(isPalindrome(word)){
console.log(word + ' is a palindrome');
}else{
console.log(word + ' is not a palindrome');
}
// 三.实现括号匹配 返回括号缺失位置
// 使用用两个栈,一个存储所有字符,一个只存储括号
// s1入栈所有字符
// 而遇到前括号,入栈s2;遇到后括号,查看s2最顶部的括号是否匹配
// 若匹配则让s2出栈该后括号匹配的前括号,即最顶部的括号
// 若不匹配,则返回括号不匹配或缺失的位置
function isMatch(str){
const s1 = new Stack();
const s2 = new Stack();
let num = '';
const sign1 = '+-*/()[]{}';
const sign2 = '()[]{}';
for(var i = 0;i<str.length;i++){
if(sign2.indexOf(str[i]) > -1){
switch(str[i]){
case'(':
case'[':
case'{':s2.push(str[i]);break;
case')':
if(s2.peek() != "("){
return `在${s1.peek()}后不匹配`
};
s2.pop();
break;
case']':
if(s2.peek() != "["){
return `在${s1.peek()}后不匹配`
};
s2.pop();
break;
case'}':
if(s2.peek() != "{"){
return `在${s1.peek()}后不匹配`
};
s2.pop();
break;
}
}
if(sign1.indexOf(str[i])>-1){
s1.push(str[i]);
continue;
}
while('0'<= str[i] && str[i] <= '9' || str[i] == '.'){
num += str[i];
i++
}
i--;
s1.push(num);
num='';
}
return s2.length() > 0 ? `在末尾,${s1.peek()}后不匹配` : '匹配';
}
console