【LeetCode】C# 20、Valid Parentheses

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 stack = new Stack();
            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# 20、Valid Parentheses_第1张图片

你可能感兴趣的:(leetcode)