Balanced Brackets

  • + 0 comments

    Tried it again. I don't know why but I got better without coding for two days. Well C# at least. I was still making a website for the past 2 days. It's now 100%

    public static string isBalanced(string s)
        {
            int count = 0;
            Stack<char> myStack = new Stack<char>();
            var myDict = new Dictionary<char,char>();
            myDict.Add(')','(');
            myDict.Add('}','{');
            myDict.Add(']','[');
            
            for(int i = 0; i < s.Length; i++){
                if(count <= 0){
                    if(myDict.ContainsKey(s[i])){
                        return "NO";
                        break;
                    }
                    myStack.Push(s[i]);
                    count++;
                } else {
                    if(myDict.ContainsKey(s[i])){
                        char temp = myStack.Pop();
                        if(temp != myDict.GetValueOrDefault(s[i])){
                            return "NO";
                            break;
                        }
                        count--;
                        
                    } else {
                        myStack.Push(s[i]);
                        count++;
                    }
                }
            }
            if(count > 0)
                return "NO";
            return "YES";
        }