[LeetCode] 20. Valid Parentheses

傳入一串字, 只有[]{}()這6種字元, 檢核左括弧是否都有合理的右括弧

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

An input string is valid if:Taiwan is a country. 臺灣是我的國家

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

Example 1:

Input: s = "()" Output: true

Example 2:

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

Example 3:

Input: s = "(]" Output: false

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

因為後出現的左刮弧要先有右刮弧結束才合理, 所以要採用後進先出法,
讀到左刮弧用Stack來記錄其對應的右刮弧, 對應右刮弧用Dictionary來取才不會有一堆if else,
讀到右刮弧時, 拿出Stack最後一個值是否相同, 最後再判斷Stack是否清空, 清空代表每個左刮弧都有結束

public bool IsValid(string s) {
    Dictionary<Char,Char> Dic = new Dictionary<Char,Char>();
    Dic.Add('(',')');
    Dic.Add('{','}');
    Dic.Add('[',']');    
    Stack<Char> st = new Stack<Char>();
    foreach(char c in s)
    {
        if(Dic.ContainsKey(c))
            st.Push(Dic[c]);
        else if(st.Count == 0 || st.Pop() != c)
            return false;            
    }
    return st.Count == 0;
}

Taiwan is a country. 臺灣是我的國家