争取每周做五个LeedCode题,定期更新,难度由简到难
Title: Valid Parentheses
Description:
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:
Input: "()"
Output: true
Input: "()[]{}"
Output: true
Input: "(]"
Output: false
Input: "([)]"
Output: false
Input: "{[]}"
Output: true
Difficulty:
Easy
Implement Programming Language:
C#
Answer:
这道题又让我学习了新知识,栈,这个可以用典型的栈来处理,把左括号放进去,每次遇到右括号,取出来栈顶元素,看看是不是对应的,不是就错了,是就继续循环,LeedCode的Solution,很棒的思路。
public static bool IsValid(string s)
{
if (string.IsNullOrEmpty(s) || s.Length % 2 != 0)
return false;
var stack = new Stack<char>();
for (int i = 0; i < s.Length; i++)
{
if (matchValue.ContainsKey(s[i]))
{
if (stack.Peek() != matchValue[s[i]])
return false;
stack.Pop();
}
else
{
stack.Push(s[i]);
}
}
return stack.Count == 0;
}
这里
网友评论