Tuesday, August 25, 2015

Leetcode: Valid Parentheses (0ms)(string)(stack)

PROBLEM:
https://leetcode.com/problems/valid-parentheses/

--------------------------------

1. using stack to temporally store the characters;
2. when meet [, {, (, push to stack;
3. when meet }, ], ), compare with the top of stack;
        if it's a pair, pop the top one (delete the top one);
        if it's not a pair, it's failed. 
4. if in the final, nothing it's left, it's true. 

See codes for details. 



/////////////////////////////////////////////////////////
// codes 0ms
class Solution {
public:
       bool isValid(string s) {
              stack<char> sta;
              sta.push('0');
              for (auto c : s){
                     switch (c) {
                     case '{':
                           sta.push('{');
                           break;
                     case '}':
                           if (sta.top() != '{') return false;
                           else sta.pop();
                           break;
                     case '[':
                           sta.push('[');
                           break;
                     case ']':
                           if (sta.top() != '[') return false;
                           else sta.pop();
                           break;
                     case '(':
                           sta.push('(');
                           break;
                     case ')':
                           if (sta.top() != '(') return false;
                           else sta.pop();
                           break;
                     default:;
                     }
              }
              if (sta.top() == '0')return true;
              else return false;
       }

};

No comments:

Post a Comment