本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
C++实现LeetCode(20.验证括号)
sz199511 · 162浏览 · 发布于2021-07-13 +关注

这篇文章主要介绍了C++实现LeetCode(20.验证括号),本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

[LeetCode] 20. Valid Parentheses 验证括号

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.

  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

这道题让我们验证输入的字符串是否为括号字符串,包括大括号,中括号和小括号。这里需要用一个栈,开始遍历输入字符串,如果当前字符为左半边括号时,则将其压入栈中,如果遇到右半边括号时,若此时栈为空,则直接返回 false,如不为空,则取出栈顶元素,若为对应的左半边括号,则继续循环,反之返回 false,代码如下:

 方法一:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

class Solution {

public:

    bool isValid(string s) {

        stack<char> parentheses;

        for (int i = 0; i < s.size(); ++i) {

            if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]);

            else {

                if (parentheses.empty()) return false;

                if (s[i] == ')' && parentheses.top() != '(') return false;

                if (s[i] == ']' && parentheses.top() != '[') return false;

                if (s[i] == '}' && parentheses.top() != '{') return false;

                parentheses.pop();

            }

        }

        return parentheses.empty();

    }

};

方法二:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

class Solution {

public:

    bool isValid(string s) {

        int n = s.size();

        if (n % 2 == 1) {

            return false;

        }


        unordered_map<char, char> pairs = {

            {')', '('},

            {']', '['},

            {'}', '{'}

        };

        stack<char> stk;

        for (char ch: s) {

            if (pairs.count(ch)) {

                if (stk.empty() || stk.top() != pairs[ch]) {

                    return false;

                }

                stk.pop();

            }

            else {

                stk.push(ch);

            }

        }

        return stk.empty();

    }

};


c++

相关推荐

PHP实现部分字符隐藏

沙雕mars · 1325浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别

kenrry1992 · 908浏览 · 2019-05-08 21:14:54
Tomcat 下载及安装配置

manongba · 970浏览 · 2019-05-13 21:03:56
JAVA变量介绍

manongba · 962浏览 · 2019-05-13 21:05:52
什么是SpringBoot

iamitnan · 1086浏览 · 2019-05-14 22:20:36
加载中

0评论

评论
不积跬步无以至千里,不积小流无以成江海!
分类专栏
小鸟云服务器
扫码进入手机网页