zoukankan      html  css  js  c++  java
  • Leetcode 20. Valid Parentheses

    20. Valid Parentheses

    • Total Accepted: 128586
    • Total Submissions: 418560
    • Difficulty: Easy

    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.

    思路:利用栈来判断配对的括号,如果都可以配对成功,最后栈的元素数量应该为0。题目给定的字符串只包含括号,所以每次遇到是(', '{'或者'[',直接入栈;遇到']',')'或者']',只有当栈不为空&&栈顶元素与之配对时,才弹出栈,否则直接返回false。

    代码:

     1 class Solution {
     2 public:
     3     bool isValid(string s) {
     4         stack<char> cs;
     5         unordered_map<char, char> um;
     6         um['('] = ')';
     7         um['{'] = '}';
     8         um['['] = ']';
     9         for (int i = 0; i < s.size(); i++) {
    10             if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
    11                 cs.push(s[i]);
    12                 continue;
    13             }
    14             if (!cs.empty() && um[cs.top()] == s[i]){
    15                 cs.pop();
    16                 continue;
    17             } 
    18             return false;
    19         }
    20         return cs.empty();
    21     }
    22 };
  • 相关阅读:
    474 Ones and Zeroes 一和零
    473 Matchsticks to Square 火柴拼正方形
    472 Concatenated Words 连接的单词
    Django 视图系统
    Django 路由系统
    Django 框架基础
    jQuery
    JavaScript- BOM, DOM
    CSS概念,引入,选择器
    HTML
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5838714.html
Copyright © 2011-2022 走看看