数据结构-队列和堆栈-javascript应用

 

 1 // 堆栈和队列判断回文字符串
 2 // js 队列的数组实现:arr.push()=>入队,arr.shift()=>出队
 3 // js 堆栈的数组实现: arr.unshift() =>入栈,arr.shift() => 出栈
 4 let hStr = 'abcdedcba';
 5 function isHW(hStr) {
 6     let queue = hStr.split("");
 7     let stack = hStr.split("");
 8     console.log(queue);
 9     console.log(stack);
10     let len = queue.length;
11     let i;
12     for (i = 0; i < len; i++) {
13         if (queue.pop() != stack.shift()) {
14             return false;
15         }
16     }
17     return true;
18 }
19 
20 let result = isHW(hStr);
21 console.log(result);

 

 

 1 // 利用栈判断左右括号是否匹配
 2 function validSymbol(str) {
 3     debugger;
 4     let leftS = ['(', '{', '['];
 5     let rightS = [')', '}', ']'];
 6 
 7     let leftStack = [];
 8     let lIndex = -1;
 9     let rIndex = -1;
10     for (let s in str) {
11         lIndex = leftS.indexOf(str[s]);
12         rIndex = rightS.indexOf(str[s]);
13         if (lIndex != -1) {
14             leftStack.unshift(lIndex);
15         } else if (rIndex != -1) {
16             if (rIndex != leftStack.shift()) {
17                 return false;
18             }
19         }
20     }
21     return true;
22 }
23 let result = validSymbol("{[())]}");
24 console.log(result)

 

posted @ 2018-05-24 11:16  veryvalley  阅读(116)  评论(0编辑  收藏  举报