【leetcode系列】20.有效的括號

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

 

題目描述

1Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
 2
 3An input string is valid if:
 4
 5Open brackets must be closed by the same type of brackets.
 6Open brackets must be closed in the correct order.
 7Note that an empty string is also considered valid.
 8
 9Example 1:
10
11Input: "()"
12Output: true
13Example 2:
14
15Input: "()[]{}"
16Output: true
17Example 3:
18
19Input: "(]"
20Output: false
21Example 4:
22
23Input: "([)]"
24Output: false
25Example 5:
26
27Input: "{[]}"
28Output: true

思路

關於這道題的思路,鄧俊輝講的很是好,沒有看過的同窗能夠看一下, 視頻地址。javascript

使用棧,遍歷輸入字符串php

若是當前字符爲左半邊括號時,則將其壓入棧中java

若是遇到右半邊括號時,分類討論:數組

1)如棧不爲空且爲對應的左半邊括號,則取出棧頂元素,繼續循環app

2)若此時棧爲空,則直接返回falseide

3)若不爲對應的左半邊括號,反之返回falsespa

 

值得注意的是,若是題目要求只有一種括號,那麼咱們其實能夠使用更簡潔,更省內存的方式 - 計數器來進行求解,而
沒必要要使用棧。code

事實上,這類問題還能夠進一步擴展,咱們能夠去解析相似HTML等標記語法, 好比視頻

 

 

關鍵點解析

  1. 棧的基本特色和操做blog

  2. 若是你用的是JS沒有現成的棧,能夠用數組來模擬
    入:push 出: pop

入:push 出 shift 就是隊列

代碼

  • 語言支持:JS,Python

Javascript Code:

1/*
 2 * @lc app=leetcode id=20 lang=javascript
 3 *
 4 * [20] Valid Parentheses
 5 *
 6 * https://leetcode.com/problems/valid-parentheses/description/
 7 *
 8 * algorithms
 9 * Easy (35.97%)
10 * Total Accepted:    530.2K
11 * Total Submissions: 1.5M
12 * Testcase Example:  '"()"'
13 *
14 * Given a string containing just the characters '(', ')', '{', '}', '[' and
15 * ']', determine if the input string is valid.
16 * 
17 * An input string is valid if:
18 * 
19 * 
20 * Open brackets must be closed by the same type of brackets.
21 * Open brackets must be closed in the correct order.
22 * 
23 * 
24 * Note that an empty string is also considered valid.
25 * 
26 * Example 1:
27 * 
28 * 
29 * Input: "()"
30 * Output: true
31 * 
32 * 
33 * Example 2:
34 * 
35 * 
36 * Input: "()[]{}"
37 * Output: true
38 * 
39 * 
40 * Example 3:
41 * 
42 * 
43 * Input: "(]"
44 * Output: false
45 * 
46 * 
47 * Example 4:
48 * 
49 * 
50 * Input: "([)]"
51 * Output: false
52 * 
53 * 
54 * Example 5:
55 * 
56 * 
57 * Input: "{[]}"
58 * Output: true
59 * 
60 * 
61 */
62/**
63 * @param {string} s
64 * @return {boolean}
65 */
66var isValid = function(s) {
67    let valid = true;
68    const stack = [];
69    const mapper = {
70        '{': "}",
71        "[": "]",
72        "(": ")"
73    }
74
75    for(let i in s) {
76        const v = s[i];
77        if (['(', '[', '{'].indexOf(v) > -1) {
78            stack.push(v);
79        } else {
80            const peak = stack.pop();
81            if (v !== mapper[peak]) {
82                return false;
83            }
84        }
85    }
86
87    if (stack.length > 0) return false;
88
89    return valid;
90};

Python Code:

1    class Solution:
 2        def isValid(self,s):
 3          stack = []
 4          map = {
 5            "{":"}",
 6            "[":"]",
 7            "(":")"
 8          }
 9          for x in s:
10            if x in map:
11              stack.append(map[x])
12            else:
13              if len(stack)!=0:
14                top_element = stack.pop()
15                if x != top_element:
16                  return False
17                else:
18                  continue
19              else:
20                return False
21          return len(stack) == 0

擴展

若是讓你檢查XML標籤是否閉合如何檢查, 更進一步若是要你實現一個簡單的XML的解析器,應該怎麼實現?

相關文章
相關標籤/搜索