// 1. 设计一个括号是否匹配的方法 (栈)
function bracketMatch(str) {
const length = str.length;
if (length === 0) {
return true
}
const stack = []; // 借助数组模拟栈
const leftBracket = '([{'; // 定义左括号
const rightBracket = ')]}'; // 定义右括号
for (let index = 0; index < length; index++) {
const s = str[index];
if (leftBracket.includes(s)) {
// 如果出现左括号,压栈
stack.push(s)
} else if (rightBracket.includes(s)) {
// 如果出现右括号,需要判断栈顶元素与之是否匹配,是否需要出栈
const top = stack[stack.length - 1]; // 栈顶元素
// 左右括号是否匹配
if (isMatch(top, s)) {
stack.pop(); // 出栈,注意这儿没有压栈操作
}
}
}
return stack.length === 0; // 长度为 0 代表括号匹配
}
// 判断左右括号是否匹配
function isMatch(left, right) {
if (left === '{' && right === '}') {
return true;
} else if (left === '[' && right === ']') {
return true;
} else if (left === '(' && right === ')') {
return true;
} else {
return false
}
}
console.log(bracketMatch('([{}])'));
console.log(bracketMatch('([{})'));
// 2.判断当前字符串是不是回文数 (栈) 不要用reverse方法
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";
var word2 = "raccr";
console.log(isPalindrome(word1));
console.log(isPalindrome(word2));
// 进制转换(十转任意进制)(栈)
var Stack = (function () {
var items = new WeakMap();
//先入后出,后入先出
class Stack {
constructor() {
items.set(this, []);
}
push(ele) {
//入栈
var ls = items.get(this);
ls.push(ele);
}
pop() {
//出栈
var ls = items.get(this);
return ls.pop();
}
size() {
//获取栈的长度
var ls = items.get(this);
return ls.length;
}
print() {
//打印栈
var ls = items.get(this);
return ls.toString();
}
}
return Stack;
})();
function devide(num, base) {
base = Math.floor(base) || 2;
if (typeof num != "number" || num < 0 || base > 16 || base < 2) {
throw new Error("参数错误");
return '';
}
num = Math.floor(num);
var code = "0123456789ABCDEF";
var stack = new Stack();
var res = '';
var rem;
while (num > 0) {
rem = num % base;
stack.push(rem);
num = Math.floor(num / base);
}
while (stack.size() > 0) {
res += code[stack.pop()];
}
return res;
}
console.log(devide(16, 2))