C# 寫 LeetCode easy #20 Valid Parentheses

20、Valid Parentheseside

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

An input string is valid if:code

  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.blog

Example 1:字符串

Input: "()"
Output: true

Example 2:input

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

Example 3:string

Input: "(]"
Output: false

Example 4:it

Input: "([)]"
Output: false

Example 5:io

Input: "{[]}"
Output: true

代碼:
static void Main(string[] args)
{
    string str = "({}[])";
    bool res = IsValid(str);
    Console.WriteLine(res);
    Console.ReadKey();
}

private static bool IsValid(string s)
{
    if (s.Length % 2 != 0) return false;
    Dictionary<char, char> dic = new Dictionary<char, char>() {
                { ')','('},
                { ']','['},
                { '}','{'}
            };
    var stack = new Stack<char>();
    foreach (var str in s)
    {
        if (dic.ContainsKey(str))
        {
            if (stack.Count != 0 && stack.Peek() == dic[str])
            {
                stack.Pop();
            }
            else
            {
                return false;
            }
        }
        else
        {
            stack.Push(str);
        }
    }
    return stack.Count == 0;
}

 

解析:class

輸入:字符串

輸出:bool類型

思想

  首先,這種匹配問題,都放在棧中,棧特色是先進後出。這裏以鍵值對的形式把匹配項存入字典中。另外奇數個字符是不對的。

  其次,剛開始棧空,將向右方向的字符((,{,[)所有存入棧中,而後若出現一個向左方向的,就在棧中匹配,判斷是否與棧頂元素匹配。若匹配,則移出。不然返回false。

  最後,判斷棧中是否將所有元素匹配完畢,即都被移出,返回bool結果。

時間複雜度:O(n)

相關文章
相關標籤/搜索