1. 程式人生 > 實用技巧 >leetcode(2)-有效的括號

leetcode(2)-有效的括號

題目描述:

給定一個只包括 '(',')','{','}','[',']'的字串,判斷字串是否有效。

有效字串需滿足:

左括號必須用相同型別的右括號閉合。
左括號必須以正確的順序閉合。
注意空字串可被認為是有效字串。

示例:

輸入: "()"
輸出: true

輸入: "(]"
輸出: false

輸入: "([)]"
輸出: false

程式碼:

functionisValid(s:string):boolean{ constmap=newMap(); map.set('{','}'); map.set('[',']'); map.set('(',')'); conststack:string[]=[]; for(letiofs){ constvalue=map.get(i); if(value){ stack.push(value); }else{ lettop=stack.pop(); if(i!=top)returnfalse } } if(stack.length){ returnfalse }else{ returntrue } };