leetCode-0020_有效的括号

题目描述

英文题目

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:

1
2
Input: "()"
Output: true

Example 2:

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

Example 3:

1
2
Input: "(]"
Output: false

Example 4:

1
2
Input: "([)]"
Output: false

Example 5:

1
2
Input: "{[]}"
Output: true
中文题目

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

1
2
输入: "()"
输出: true

示例 2:

1
2
输入: "()[]{}"
输出: true

示例 3:

1
2
输入: "(]"
输出: false

示例 4:

1
2
输入: "([)]"
输出: false

示例 5:

1
2
输入: "{[]}"
输出: true

解决方法

方法一
  • 描述

我们需要用一个栈,我们开始遍历输入字符串,如果当前字符为左半边括号时,则将其压入栈中,如果遇到右半边括号时,若此时栈为空,则直接返回false,如不为空,则取出栈顶元素,若为对应的左半边括号,则继续循环,反之返回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
bool isValid(char* s) {
//栈
char a[10000];
int top = -1;
int i = 0;

while(*s != '\0') {
if (*s == '[' || *s == '{' || *s == '(') {
a[i] = *s;
i++;
top++;
}
else if (*s == ']') {
if (i != 0 && a[--i] == '[') {
top--;
}
else {
return false;
}
}
else if (*s == '}') {
if (i != 0 && a[--i] == '{') {
top--;
}
else {
return false;
}
}
else if (*s == ')') {
if (i != 0 && a[--i] == '(') {
top--;
}
else {
return false;
}
}
s++;
}
return top == -1;
}

void test(void)
{
int flag = isValid("{[]}");
printf("flag = %d\n",flag);
}

题目来源

Valid Parentheses

有效的括号