C# 写 LeetCode easy #20 Valid Parentheses
20、Valid Parentheses
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- 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
代码:
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; }
解析:
输入:字符串
输出:bool类型
思想:
首先,这种匹配问题,都放在栈中,栈特点是先进后出。这里以键值对的形式把匹配项存入字典中。另外奇数个字符是不对的。
其次,刚开始栈空,将向右方向的字符((,{,[)全部存入栈中,然后若出现一个向左方向的,就在栈中匹配,判断是否与栈顶元素匹配。若匹配,则移出。否则返回false。
最后,判断栈中是否将全部元素匹配完毕,即都被移出,返回bool结果。
时间复杂度:O(n)