首页 > 代码库 > leetcode20

leetcode20

public class Solution {
    Stack<char> S = new Stack<char>();

        public bool IsValid(string s)
        {
            foreach (var c in s)
            {
                if (c == ( || c == [ || c == {)
                {
                    S.Push(c);
                }
                else if(c == ))                
                {
                    if (S.Count > 0)
                    {
                        var k = S.Peek();
                        if (k == ()
                        {
                            S.Pop();
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else if (c == ])
                {
                    if (S.Count > 0)
                    {
                        var k = S.Peek();
                        if (k == [)
                        {
                            S.Pop();
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else if (c == })
                {
                    if (S.Count > 0)
                    {
                        var k = S.Peek();
                        if (k == {)
                        {
                            S.Pop();
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            if (S.Count > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
}

https://leetcode.com/problems/valid-parentheses/#/description

leetcode20