1. 程式人生 > >【LeetCode】20. Valid Parentheses - Java實現

【LeetCode】20. Valid Parentheses - Java實現

文章目錄

1. 題目描述:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

2. 思路分析:

題目的意思是給定一個包含一系列括號的字串,判斷其中的括號是否兩兩匹配。

括號匹配問題,很自然地想到用棧來處理,即遍歷字串,遇到左括號就入棧,遇到右括號,則出棧並判斷與當前的右括號是否匹配。

3. Java程式碼:

原始碼見我GiHub主頁

程式碼:

public static boolean isValid(String s) {
    Stack<Character> stack = new Stack<>();
    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        // 如果是左括號,則入棧
        if
(ch == '(' || ch == '[' || ch == '{') { stack.push(ch); } else { // 如果是右括號,則比較其與棧頂元素是否配對 if (stack.isEmpty()) { return false; } if (ch == ')' && stack.peek() != '(') { return false; } if (ch == ']' && stack.peek() != '[') { return false; } if (ch == '}' && stack.peek() != '{') { return false; } stack.pop(); } } // 最後棧為空則表示完全匹配完畢 return stack.isEmpty(); }