Skip to content

Commit 455f8fc

Browse files
committed
<添加>(leetcode): 添加答案
1 parent 5428139 commit 455f8fc

8 files changed

Lines changed: 632 additions & 0 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# 有效的括号
2+
3+
> 视频地址 https://www.bilibili.com/video/av55398985/?p=9
4+
5+
![](https://raw.githubusercontent.com/gaohanghang/images/master/img20190625212101.png)
6+
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package a20_有效的括号.极客时间;
2+
3+
/**
4+
* @Description 时间复杂度 n^2 / 2
5+
* @Author Gao Hang Hang
6+
* @Date 2019-06-25 21:17
7+
**/
8+
public class Solution {
9+
public boolean isValid(String s) {
10+
int length;
11+
do {
12+
length = s.length();
13+
s = s.replace("()", "").replace("{}", "").replace("[]", "");
14+
} while (length != s.length());
15+
return s.length() == 0;
16+
}
17+
18+
public static void main(String[] args) {
19+
new Solution().isValid("{()}");
20+
}
21+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package a20_有效的括号.题解;
2+
3+
import java.util.HashMap;
4+
import java.util.Stack;
5+
6+
/**
7+
* @Description
8+
* @Author Gao Hang Hang
9+
* @Date 2019-06-25 21:51
10+
**/
11+
public class Solution {
12+
13+
// Hash table that takes care of the mappings. 负责映射的哈希表。
14+
private HashMap<Character, Character> mappings;
15+
16+
// Initialize hash map with mappings. This simply makes the code easier to read.
17+
// 使用映射初始化h ash map。这简单地方式使代码更容易阅读。
18+
public Solution() {
19+
this.mappings = new HashMap<Character, Character>();
20+
this.mappings.put(')', '(');
21+
this.mappings.put('}', '{');
22+
this.mappings.put(']', '[');
23+
}
24+
25+
public boolean isValid(String s) {
26+
27+
// Initialize a stack to be used in the algorithm. 初始化一个栈
28+
Stack<Character> stack = new Stack<Character>();
29+
30+
for (int i = 0; i < s.length(); i++) {
31+
char c = s.charAt(i);
32+
33+
// If the current character is a closing bracket. 如果当前字符是结束括号
34+
if (this.mappings.containsKey(c)) {
35+
36+
// Get the top element of the stack. If the stack is empty, set a dummy value of '#'
37+
// 获取栈的顶部元素。如果栈为空,请设置虚拟值“#”
38+
char topElement = stack.empty() ? '#' : stack.pop();
39+
40+
// If the mapping for this bracket doesn't match the stack's top element, return false.
41+
// 如果此括号的映射与栈的top元素不匹配,则返回false。
42+
if (topElement != this.mappings.get(c)) return false;
43+
} else {
44+
// If it was an opening bracket, push to the stack. 如果它是一个左括号,推到栈。
45+
stack.push(c);
46+
}
47+
}
48+
49+
// If the stack still contains elements, then it is an invalid expression.
50+
// 如果栈仍然包含元素,那么它是一个无效的表达式。
51+
return stack.isEmpty();
52+
}
53+
}
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
# 有效的括号
2+
3+
**思路**
4+
5+
想象一下,你正在为你的大学课设编写一个小型编译器,编译器的任务之一(或称子任务)将检测括号是否匹配。
6+
7+
我们本文中看到的算法可用于处理编译器正在编译的程序中的所有括号,并检查是否所有括号都已配对。这将检查给定的括号字符串是否有效,是一个重要的编程问题。
8+
9+
我们这个问题中将要处理的表达式可以包含以下三种不同类型的括号:
10+
11+
- `()`
12+
- `{}` 以及
13+
- `[]`
14+
15+
在查看如何检查由这些括号组成的给定表达式是否有效之前,让我们看一下该问题的简化版本,在简化后的问题中,只含一种类型的括号。这么一来,我们将会遇到的表达式是
16+
17+
```
18+
(((((()))))) -- VALID
19+
20+
()()()() -- VALID
21+
22+
(((((((() -- INVALID
23+
24+
((()(()))) -- VALID
25+
```
26+
27+
上我们试着用一个简单的算法来解决这一问题。
28+
29+
1. 我们从表达式的左侧开始,每次只处理一个括号。
30+
2. 假设我们遇到一个开括号(即 `(`),表达式是否无效取决于在该表达式的其余部分的某处是否有相匹配的闭括号(即 `)`)。此时,我们只是增加计数器的值保持跟踪现在为止开括号的数目。`left += 1`
31+
3. 如果我们遇到一个闭括号,这可能意味着这样两种情况:
32+
1. 此闭括号没有与与之对应的开括号,在这种情况下,我们的表达式无效。当 `left == 0`,也就是没有未配对的左括号可用时就是这种情况。
33+
2. 我们有一些未配对的开括号可以与该闭括号配对。当 `left > 0`,也就是有未配对的左括号可用时就是这种情况。
34+
4. 如果我们在 `left == 0` 时遇到一个闭括号(例如 `)`),那么当前的表达式无效。否则,我们会减少 `left` 的值,也就是减少了可用的未配对的左括号的数量。
35+
5. 继续处理字符串,直到处理完所有括号。
36+
6. 如果最后我们仍然有未配对的左括号,这意味着表达式无效。
37+
38+
在这里讨论这个特定算法是因为我们从该解决方案中获得灵感以解决原始问题。为了更好地理解我们讨论的算法,请观看下面的动画演示。
39+
40+
![](https://raw.githubusercontent.com/gaohanghang/images/master/imgKapture%202019-06-25%20at%2021.42.16.gif)
41+
42+
如果我们只是尝试对原始问题采用相同的办法,这是根本就行不通的。基于简单计数器的方法能够在上面完美运行是因为所有括号都具有相同的类型。因此,当我们遇到一个闭括号时,我们只需要假设有一个对应匹配的开括号是可用的,即假设 `left > 0`
43+
44+
但是,在我们的问题中,如果我们遇到 `]`,我们真的不知道是否有相应的 `[` 可用。你可能会问:
45+
46+
> 为什么不为不同类型的括号分别维护一个单独的计数器?
47+
48+
这可能不起作用,因为括号的相对位置在这里也很重要。例如:
49+
50+
```
51+
[{]
52+
```
53+
54+
如果我们只是在这里维持计数器,那么只要我们遇到闭合方括号,我们就会知道此处有一个可用的未配对的开口方括号。但是,**最近的未配对的开括号是一个花括号,而不是一个方括号**,因此计数方法在这里被打破了。
55+
56+
## 方法1: 栈
57+
58+
关于有效括号表达式的一个有趣属性是有效表达式的子表达式也应该是有效表达式。(不是每个子表达式)例如
59+
60+
![](https://raw.githubusercontent.com/gaohanghang/images/master/img20190625214342.png)
61+
62+
此外,如果仔细查看上述结构,颜色标识的单元格将标记开闭的括号对。整个表达式是有效的,而它的子表达式本身也是有效的。这为问题提供了一种递归结构。例如,考虑上图中两个绿色括号内的表达式。开括号位于索引 `1`,相应闭括号位于索引 `6`
63+
64+
> 如果每当我们在表达式中遇到一对匹配的括号时,我们只是从表达式中删除它,会发生什么?
65+
66+
让我们看看下面的这个想法,从整体表达式中一次删除一个较小的表达式,因为这是一个有效的表达式,我们最后剩留下一个空字符串。
67+
68+
![](https://raw.githubusercontent.com/gaohanghang/images/master/imgKapture%202019-06-25%20at%2021.44.54.gif)
69+
70+
> 在表示问题的递归结构时,栈数据结构可以派上用场。我们无法真正地从内到外处理这个问题,因为我们对整体结构一无所知。但是,栈可以帮助我们递归地处理这种情况,即从外部到内部。
71+
72+
让我们看看使用栈作为该问题的中间数据结构的算法。
73+
74+
**算法**
75+
76+
1. 初始化栈 S。
77+
2. 一次处理表达式的每个括号。
78+
3. 如果遇到开括号,我们只需将其推到栈上即可。这意味着我们将稍后处理它,让我们简单地转到前面的 **子表达式**
79+
4. 如果我们遇到一个闭括号,那么我们检查栈顶的元素。如果栈顶的元素是一个 `相同类型的` 左括号,那么我们将它从栈中弹出并继续处理。否则,这意味着表达式无效。
80+
5. 如果到最后我们剩下的栈中仍然有元素,那么这意味着表达式无效。
81+
82+
我们来看一下该算法的动画演示,然后转到实现部分。
83+
84+
![](https://raw.githubusercontent.com/gaohanghang/images/master/imgKapture%202019-06-25%20at%2021.48.58.gif)
85+
86+
现在让我们看看该算法是如何实现的。
87+
88+
```java
89+
public class Solution {
90+
91+
// Hash table that takes care of the mappings. 负责映射的哈希表。
92+
private HashMap<Character, Character> mappings;
93+
94+
// Initialize hash map with mappings. This simply makes the code easier to read.
95+
// 使用映射初始化h ash map。这简单地方式使代码更容易阅读。
96+
public Solution() {
97+
this.mappings = new HashMap<Character, Character>();
98+
this.mappings.put(')', '(');
99+
this.mappings.put('}', '{');
100+
this.mappings.put(']', '[');
101+
}
102+
103+
public boolean isValid(String s) {
104+
105+
// Initialize a stack to be used in the algorithm. 初始化一个栈
106+
Stack<Character> stack = new Stack<Character>();
107+
108+
for (int i = 0; i < s.length(); i++) {
109+
char c = s.charAt(i);
110+
111+
// If the current character is a closing bracket. 如果当前字符是结束括号
112+
if (this.mappings.containsKey(c)) {
113+
114+
// Get the top element of the stack. If the stack is empty, set a dummy value of '#'
115+
// 获取栈的顶部元素。如果栈为空,请设置虚拟值“#”
116+
char topElement = stack.empty() ? '#' : stack.pop();
117+
118+
// If the mapping for this bracket doesn't match the stack's top element, return false.
119+
// 如果此括号的映射与栈的top元素不匹配,则返回false。
120+
if (topElement != this.mappings.get(c)) return false;
121+
} else {
122+
// If it was an opening bracket, push to the stack. 如果它是一个左括号,推到栈。
123+
stack.push(c);
124+
}
125+
}
126+
127+
// If the stack still contains elements, then it is an invalid expression.
128+
// 如果栈仍然包含元素,那么它是一个无效的表达式。
129+
return stack.isEmpty();
130+
}
131+
}
132+
```
133+
134+
**复杂度分析**
135+
136+
- 时间复杂度:O(n),因为我们一次只遍历给定的字符串中的一个字符并在栈上进行 O(1) 的推入和弹出操作。
137+
- 空间复杂度:O(n),当我们将所有的开括号都推到栈上时以及在最糟糕的情况下,我们最终要把所有括号推到栈上。例如 `((((((((((`
138+
139+
## 方法2: 替换
140+
141+
```java
142+
public class Solution {
143+
public boolean isValid(String s) {
144+
int length;
145+
do {
146+
length = s.length();
147+
s = s.replace("()", "").replace("{}", "").replace("[]", "");
148+
} while (length != s.length());
149+
return s.length() == 0;
150+
}
151+
}
152+
```
153+
154+
**复杂度分析**
155+
156+
- 时间复杂度:O(n^2 / 2)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
## Stack.Peek 与 stack.pop 的区别
2+
3+
相同点:大家都返回栈顶的值。
4+
5+
不同点:peek 不改变栈的值(不删除栈顶的值),pop会把栈顶的值删除。
6+
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package a232_用栈实现队列.解法1;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
* @Description
7+
* @Author Gao Hang Hang
8+
* @Date 2019-06-17 23:14
9+
**/
10+
public class MyQueue {
11+
12+
private Stack<Integer> s1 = new Stack<>();
13+
private Stack<Integer> s2 = new Stack<>();
14+
15+
16+
/** Initialize your data structure here. */
17+
public MyQueue() {
18+
19+
}
20+
21+
/** Push element x to the back of queue. */
22+
public void push(int x) {
23+
while (!s1.isEmpty())
24+
s2.push(s1.pop());
25+
s2.push(x);
26+
while (!s2.isEmpty())
27+
s1.push(s2.pop());
28+
}
29+
30+
/** Removes the element from in front of queue and returns that element. */
31+
public int pop() {
32+
return s1.pop();
33+
}
34+
35+
/** Get the front element. 获取头元素 */
36+
public int peek() {
37+
return s1.peek();
38+
}
39+
40+
/** Returns whether the queue is empty. */
41+
public boolean empty() {
42+
return s1.isEmpty();
43+
}
44+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package a232_用栈实现队列.解法2;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
* @Description
7+
* @Author Gao Hang Hang
8+
* @Date 2019-06-17 23:41
9+
**/
10+
public class MyQueue {
11+
12+
private Stack<Integer> s1 = new Stack<>();
13+
private Stack<Integer> s2 = new Stack<>();
14+
15+
private int front;
16+
17+
/** Initialize your data structure here. */
18+
public MyQueue() {
19+
20+
}
21+
22+
/** Push element x to the back of queue. */
23+
public void push(int x) {
24+
if (s1.empty())
25+
front = x;
26+
s1.push(x);
27+
}
28+
29+
/** Removes the element from in front of queue and returns that element. */
30+
public int pop() {
31+
if (s2.isEmpty()) {
32+
while (!s1.isEmpty())
33+
s2.push(s1.pop());
34+
}
35+
return s2.pop();
36+
}
37+
38+
/** Get the front element. */
39+
public int peek() {
40+
if (!s2.isEmpty()) {
41+
return s2.peek();
42+
}
43+
return front;
44+
}
45+
46+
/** Returns whether the queue is empty. */
47+
public boolean empty() {
48+
return s1.isEmpty() && s2.isEmpty();
49+
}
50+
}

0 commit comments

Comments
 (0)