您的位置:首页 > 编程语言 > C#

【LeetCode】C# 20、Valid Parentheses

2017-10-09 21:33 483 查看
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

给定一个字符串,只包含括号类的符号,判断是否每个括号都为closed,是否都符合语法。

解题关键在利用堆栈后进先出的特性。看是否每个左括号都有对应的右括号

public class Solution {
public bool IsValid(string s) {
Stack<Char> stack = new Stack<Char>();
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine(s[i]);
if (s.Length == 0) return false;
if (s[i] == '(')
{
stack.Push(')');
}
else if (s[i] == '{')
{
stack.Push('}');
}
else if (s[i] == '[')
{
stack.Push(']');
}
else if (stack.Count == 0)
return false;
else if (s[i] == stack.Peek())
{
stack.Pop();Console.WriteLine("pop");
}
else
return false;
}
if (stack.Count == 0)
return true;
return false;
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c#