括号匹配问题

新年到了,恭祝大家新年快乐

今天解决括号匹配问题

要求:

给定一个字符串,判断它是否括号匹配,'(‘和’)‘匹配,’[‘和’]‘匹配,’{‘和’}‘匹配,成对出现。例如:"( [ [ ] ] )“括号匹配,而”[ [ ( ( ) )“则不匹配。

做法:

1. 既然要括号匹配,那么奇数长度的字符串一定是不匹配的,而且后出现的符号先匹配,由此我们可以联想到栈后进先出的特点,所以这道题利用栈来解决;
2. 遍历字符串,如果遇到了'(‘ , ’[‘ , ’{‘则将它们压栈,如果遇到’)‘ , ’]‘ , ’}‘则判断它是否与栈顶元素匹配,如果匹配,则继续遍历字符串,否则返回false,说明它不匹配;当字符串遍历完了,判断栈是否为空,如果为空则括号匹配,如果不为空则括号不匹配。

代码实现

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <stack>
using namespace std;
class Solution {
public:
    bool isValid(string s) {
        if (s.length()<=0) {
            return true;
        }
        int n = (int)s.length();
        if (n%2!=0) {
            return false;
        }else{
            stack<char> stack;
            for (int i=0; i<n; i++) {
                if (s[i]=='('||s[i]=='['||s[i]=='{') {
                    stack.push(s[i]);
                }
                if (!stack.empty()) {
                    if (s[i]==')') {
                        char top = stack.top();
                        if (top=='(') {
                            stack.pop();
                            continue;
                        }else{
                            return false;
                        }
                    }
                    else if (s[i]==']') {
                        char top = stack.top();
                        if (top=='[') {
                            stack.pop();
                            continue;
                        }else{
                            return false;
                        }
                    }
                    else if (s[i]=='}') {
                        char top = stack.top();
                        if (top=='{') {
                            stack.pop();
                            continue;
                        }else{
                            return false;
                        }
                    }
                }
            }
            if (stack.empty()) {
                return true;
            }else{
                return false;
            }
            ;
        }
    }
};

Comments