[作业] 有效的括号

代码

public class Solution {
    public bool IsValid(string s) {
    if(s==string.Empty) return true;
            Stack<char> temp = new Stack<char>();
            for (int i = 0; i < s.Length; i++)
            {
                if(s[i]=='('||s[i]=='['||s[i]=='{')
                {
                    temp.Push(s[i]);
                    continue;
                }
                if(temp.Count()==0) return false;
                    switch (s[i])
                    {
                        case ')':
                            if (temp.Peek() == '(')
                            temp.Pop();
                            else return false;
                            break;
                        case ']':
                            if (temp.Peek() == '[')
                            temp.Pop();
                            else return false;
                            break;
                        case '}':
                            if (temp.Peek() == '{')
                            temp.Pop();
                            else return false;
                            break;
                    }
            }
            if(temp.Count()!=0) return false;
            return true;

    }
}

在这里插入图片描述

思路

for循环检测string中的每一个字符元素
用一个栈储存左括号
当检测到右括号时,检查栈顶元素是否匹配
若是,则弹出栈顶元素并继续循环
若不是或栈为空,则直接返回false
在循环结束后,若栈内还存有元素 说明没有右括号与之匹配,返回false
若以上检测都通过,则返回true

发布了16 篇原创文章 · 获赞 1 · 访问量 272

猜你喜欢

转载自blog.csdn.net/qq_43727054/article/details/105027798