zoukankan      html  css  js  c++  java
  • 【Leetcode】【Easy】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.

    解题思路:

    栈使用的典型题目;

    解题步骤:

    1、新建一个栈;

    2、遍历字符串:

      (1)符号的左半边,则入栈;

      (2)符号的右半边,则pop出栈顶元素,如果栈为空,则返回false;

         判断此右半边和栈顶元素是否匹配;匹配继续;不匹配则返回false;

     3、循环结束后栈为空,则true,不为空则false;

     1 class Solution {
     2 public:
     3     bool isValid(string s) {
     4         stack<char> st;
     5         int len = s.length(); 
     6         
     7         for(int i = 0; i < len; ++i) {
     8             if (s[i] == ')' || s[i] == ']' || s[i] == '}') {
     9                 if (st.empty()) 
    10                     return false;
    11                 char c = st.top();
    12                 if ((c == '(' && s[i] != ')') || 
    13                     (c == '[' && s[i] != ']') || 
    14                     (c == '{' && s[i] != '}'))
    15                     return false;
    16                 st.pop();
    17                 
    18             } else {
    19                 st.push(s[i]);
    20             }
    21         }
    22         
    23         return st.empty();
    24     }
    25 };

    附录:

    常见符号ASCII码

    C++常见容器使用及公式

  • 相关阅读:
    八皇后问题
    Catalan数与出栈顺序个数,Java编程模拟
    推荐系统中的协同过滤
    集成学习
    背包问题
    逆波兰表达式
    [leetcode]775. Global and Local Inversions
    [LeetCode]Minimum Moves to Equal Array Elements1,2
    链接属性
    常用表格属性
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4225167.html
Copyright © 2011-2022 走看看