C++ , stack


  • 0
    B

    class Solution {
    public:
    bool isValid(string s) {
    int leng = s.size();
    stack<char> left_char_stack;

          for(int i = 0 ; i<leng;i++)
          {
              if(s[i] == '('||s[i] == '['||s[i] == '{')
                  left_char_stack.push(s[i]);
              else if(left_char_stack.empty())
                  return false;
              else if((s[i] == ')'&&left_char_stack.top() == '(' )||(s[i] == ']'&&left_char_stack.top() == '[' )||(s[i] == '}'&&left_char_stack.top() == '{' ))
                  left_char_stack.pop();
              else
                  return false;
          }
          if(!left_char_stack.empty())
          return false;
          return true;
    }
    

    };


  • 0
    J

    You can replace your final 3 lines of code with

    return left_char_stack.empty()
    

    as it is equivalent and much more neat, as a rule of thumb you should never have code like
    if (boolean) return boolean
    if it's the last return statement of the function as it's equivalent to just say return boolean.


  • 0
    B

    @junqiangqian it sounds right . I just don't think much about it.


Log in to reply
 

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