Valid Parentheses(20)

20— Valid Parentheses

Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: “()”
Output: true

Example 2:

Input: “()[]{}”
Output: true

Example 3:

Input: “(]”
Output: false

Example 4:

Input: “([)]”
Output: false

Example 5:

Input: “{[]}”
Output: true

C++代码:

class Solution {
public:
    bool isValid(string s) {
      int len = s.length();
      vector<char> v;
      if(len == 0) return true;
      else if(len % 2 == 1 ) return false;
      else{
        for(int i = 0; i < len; i++) {
          if(s[i] == '(' || s[i] == '{' ||s[i] == '[') {
            v.push_back(s[i]);
          }else if(s[i] == ')'){
            if(v.empty() || v.back() != '(') return false;
            else v.pop_back();
          }else if(s[i] == '}'){
            if(v.empty() || v.back() != '{') return false;
            else v.pop_back();
          }else{
            if(v.empty()|| v.back() != '[') return false;
            else v.pop_back();
          }
        }
      }
      return v.empty();
    }
};

Complexity Analysis:

Time complexity : O( n n ).
Space complexity : O( n n ).

思路1:

  • 简单的栈的应用

猜你喜欢

转载自blog.csdn.net/kelly_fumiao/article/details/85269262