zoukankan      html  css  js  c++  java
  • [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.

    解题思路:

    用一个stack实现

     1 class Solution {
     2 public:
     3     bool isValid(string s) {
     4         for (int i = 0; i < s.size(); ++i) {
     5             switch (s[i]) {
     6                 case '(':
     7                 case '{':
     8                 case '[': {
     9                     cache.push(s[i]); 
    10                     break;
    11                 }
    12                 case ')': {
    13                     if (!isSuitable('(')) {
    14                         return false;
    15                     }
    16                     break;
    17                 }
    18                 case '}': {
    19                     if (!isSuitable('{')) {
    20                         return false;
    21                     }
    22                     break;
    23                 }
    24                 case ']': {
    25                     if (!isSuitable('[')) {
    26                         return false;
    27                     }
    28                     break;
    29                 }
    30             }
    31         }
    32         
    33         if (!cache.empty()) return false;
    34         
    35         return true;
    36     }
    37 private:
    38     stack<int> cache;
    39     bool isSuitable(int character) {
    40         if (cache.empty()) {
    41             return false;
    42         }
    43         
    44         int ch = cache.top();
    45         if (ch != character) {
    46             return false;
    47         }
    48         
    49         cache.pop();
    50         
    51         return true;
    52     }
    53 };
  • 相关阅读:
    php7.4 降级 php7.1 的坑
    python 记录网页 生成pdf
    Mac 安装常用软件环境
    python 2.7 操作 excel
    007整数反转
    006Z字形变换
    005最长回文子串
    004寻找两个正序数组的中位数
    003无重复字符的最长子串
    002两数相加
  • 原文地址:https://www.cnblogs.com/skycore/p/4958094.html
Copyright © 2011-2022 走看看