-1

I have this tricky problem that I couldn't solve :

we have a string that contains either "{}" or "[]" sequences, I want to write a function or method that checks if a string is valid: It should retrun true :

  • if a string is empty
  • if E is valid (containing only the sequences above) then {E} or [E] is valid too.
  • or if E and F are concatenantion of valid expressions, the result is also valid.

    "[{}]" // valid
    "{[}]" // invalid
    "{{[[]]}}" // valid
    "{{[[]]}}{{[[]]}}" // valid
    

I tried to solve that problem by scanning the string char by char, I didn't find the suitable algorithm then I thought about regex_match, and finally I said to myself that this kind of problem should be solved with a state machine (like EBNF).

What can you do to solve that problem ?

mch
  • 9,424
  • 2
  • 28
  • 42
Aminos
  • 754
  • 1
  • 20
  • 40

1 Answers1

0

Simple answer in C++

   static bool check(const string& sequence)
   {
      if (sequence.empty())
         return true;

      std::stack<char> stack;

      for (size_t i = 0; i < sequence.length(); ++i)
      {
         const char current = sequence.at(i);
         if (current == '{' || current == '[')
            stack.push(current);

         if (current == '}' || current == ']')
         {
            if (stack.empty())
               return false;

            char last = stack.top();
            if (current == '}' && last == '{' || current == ']' && last == '[')
               stack.pop();
            else
               return false;
         }
      }

      return stack.empty();
   }
Aminos
  • 754
  • 1
  • 20
  • 40