leetcode题目例题解析(十六)

leetcode题目例题解析(十六)

Valid Parentheses

题目描述:

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

题意解析:

判断一个括号的序列是否满足合法的序列,每一对括号内部都只能有完整的括号对

解题思路:

利用栈的思想来做

代码:

class Solution {
public:
  bool isValid(string s) {
    char stack[10000];
    int top = -1;
    int length = s.length();
    for (int i = 0; i < length; i++) {
      if (top == -1) {
    stack[++top] = s[i];
      } else {
    if (stack[top] == '('&&s[i] == ')')
      top--;
    else if (stack[top] == '{'&&s[i] == '}')
      top--;
    else if (stack[top] == '['&&s[i] == ']')
      top--;
    else
      stack[++top] = s[i];

      }
    }
    if (top == -1)
      return true;
    else
      return false;
  }
};

原题目链接:
https://leetcode.com/problems/valid-parentheses/description/

猜你喜欢

转载自blog.csdn.net/OzhangsenO/article/details/78940107
今日推荐