Simple C# O(n) solution with a help of List<>


  • 0
    R

    Main idea:
    when we find close bracket, we check for it`s correct use.
    if correct, then we delete these two brackets and continue. In other way, just return false.
    At the end we should have an empty List<> if brackets are in correct order.

    public class Solution {
        public bool IsValid(string inputWord) {
            List<char> arr = inputWord.ToList();
                
                if(arr.Count == 1 && arr.Count == 0)
                {
                    return false;
                }
    
                for(int i = 0; i < arr.Count; i++)
                {
                    if(arr[i].Equals('}'))
                    {
                        if(i != 0 && arr[i - 1].Equals('{'))
                        {
                            arr.RemoveAt(i - 1);
                            arr.RemoveAt(i - 1);
                            i -= 2;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else if (arr[i].Equals(')'))
                    {
                        if (i != 0 && arr[i - 1].Equals('('))
                        {
                            arr.RemoveAt(i - 1);
                            arr.RemoveAt(i - 1);
                            i -= 2;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else if (arr[i].Equals(']'))
                    {
                        if (i != 0 && arr[i - 1].Equals('['))
                        {
                            arr.RemoveAt(i - 1);
                            arr.RemoveAt(i - 1);
                            i -= 2;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                
                if(arr.Count == 0)
                {
                    return true;
                }
                return false;
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.