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 };
  • 相关阅读:
    1216
    构建之法 1 2 3
    复利计算
    实验总结
    0916编译原理第二次上机作业
    0909第一次作业
    linux 更新jdk
    Java中使用OpenSSL生成的RSA公私钥进行数据加解密
    quartz定时任务时间表达式说明
    IntelliJ IDEA使用说明
  • 原文地址:https://www.cnblogs.com/skycore/p/4958094.html
Copyright © 2011-2022 走看看