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
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)