1 Star 1 Fork 0

wenxuefeng/data structure

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
stack.js 2.97 KB
一键复制 编辑 原始数据 按行查看 历史
ae86 提交于 2020-03-15 16:58 +08:00 . 新增佩滋糖果案例
class Stack {
constructor() {
this.dataSource = [];
this.size = 0;
}
// clear: 清除所有元素
clear() {
this.dataSource.length = 0;
this.size = 0;
}
// push:添加新元素
push(element) {
this.dataSource[this.size++] = element;
}
// pop: 删除栈顶元素
pop() {
if (this.size > 0) {
return this.dataSource.splice(--this.size, 1)[0];
}
}
//peek: 返回当前栈顶元素
peek() {
if (this.size > 0) {
return this.dataSource[this.size - 1];
}
}
// length: 返回当前栈内元素个数
length() {
return this.size;
}
// show: 返回栈的所有元素
show() {
return this.dataSource;
}
}
//1.判断字符串是否属于回文
isPalindrome('aabbaa');
isPalindrome('aabbcc');
function isPalindrome(str) {
const strArr = str.split('');
const stack = new Stack();
let newStr = '';
while (strArr.length) {
stack.push(strArr.splice(0, 1)[0]);
}
while (stack.length()) {
newStr += stack.pop();
}
console.log(newStr);
if (newStr === str) {
console.log(str + ':是回文');
}
else console.log(str + ':不是是回文');
}
//2.判断表达式的括号是否匹配
const brackets = () => {
const stack = new Stack();
return (element) => {
switch (element) {
case '(':
case '{':
case '[':
stack.push(element);
break;
case ')':
case '}':
case ']':
const brackets = stack.peek();
if (!brackets) {
stack.push(element);
}
if ((brackets === '(' && element === ')') || brackets === '{' && element === '}' || brackets === '[' && element === ']') {
stack.pop();
}
break;
};
return stack.length();
}
}
const matchBrackets = function (str) {
const match = brackets();
for (let i = 0; i < str.length; i++) {
match(str[i]);
}
if (match('') > 0) {
console.log('匹配失败');
}
else {
console.log('匹配成功');
}
}
matchBrackets('2.3+56/78*(20}+50');
matchBrackets('(2.3+56)/78*(20+50)');
//佩滋糖果盒
const peiZ = (colors,color)=>{
const stackAll = new Stack();
const stackReset = new Stack();
const stackFilter = new Stack();
colors.forEach(color => stackAll.push(color));
while(stackAll.length()>0) {
const stackColor = stackAll.pop();
if (stackColor === color) {
stackFilter.push(stackColor);
}
else {
stackReset.push(stackColor);
}
}
while(stackReset.length()>0) {
stackAll.push(stackReset.pop());
}
console.log(stackAll);
console.log(stackFilter);
}
peiZ(['red','red','yellow','green','red','yellow','yellow','green','green'],'yellow');
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wen_xue_feng/data-structure.git
git@gitee.com:wen_xue_feng/data-structure.git
wen_xue_feng
data-structure
data structure
master

搜索帮助