Skip to content

Commit fa473c3

Browse files
author
luzhicheng
committed
更新md
更新md
1 parent b0fc841 commit fa473c3

File tree

3 files changed

+98
-3
lines changed

3 files changed

+98
-3
lines changed

leetcode_stack/main.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@
88
6. [棒球比赛](棒球比赛.md)
99
7. [比较含退格的字符串](比较含退格的字符串.md)
1010
8. [删除最外层的括号](删除最外层的括号.md)
11-
8. [删除字符串中的所有相邻重复项](删除字符串中的所有相邻重复项.md)
11+
9. [删除字符串中的所有相邻重复项](删除字符串中的所有相邻重复项.md)
12+
10. [用栈操作构建数组](用栈操作构建数组.md)

leetcode_stack/删除字符串中的所有相邻重复项.md

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,33 @@
77

88
示例:
99
```python
10-
输入:"abbbaca"
10+
输入:"abbaca"
1111
输出:"ca"
1212
解释:
13-
例如,在 "abbaca" 中,我们可以删除 "bbb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"
13+
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"
14+
```
15+
16+
代码:
17+
* 变量字符串,如果此时栈为空,元素入栈
18+
* 如果此时栈不为空,弹栈,将元素与弹栈元素比较
19+
* 如果不相等,将弹栈元素再入栈,将新元素也入栈
20+
21+
```python
22+
def removeDuplicates(S):
23+
stack = []
24+
for item in S:
25+
if not stack:
26+
stack.append(item)
27+
continue
28+
29+
while stack:
30+
ele = stack.pop()
31+
if ele == item:
32+
break
33+
else:
34+
stack.append(ele)
35+
stack.append(item)
36+
break
37+
38+
return ''.join(stack)
1439
```
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
## 用栈操作构建数组
2+
给你一个目标数组 target 和一个整数 n。每次迭代,需要从  list = {1,2,3..., n} 中依序读取一个数字。
3+
4+
请使用下述操作来构建目标数组 target :
5+
* Push:从 list 中读取一个新元素, 并将其推入数组中。
6+
* Pop:删除数组中的最后一个元素。
7+
* 如果目标数组构建完成,就停止读取更多元素。
8+
* 题目数据保证目标数组严格递增,并且只包含 1 到 n 之间的数字。
9+
* 请返回构建目标数组所用的操作序列。
10+
* 题目数据保证答案是唯一的。
11+
12+
示例:
13+
```python
14+
输入:target = [1,3], n = 3
15+
输出:["Push","Push","Pop","Push"]
16+
解释:
17+
读取 1 并自动推入数组 -> [1]
18+
读取 2 并自动推入数组,然后删除它 -> [1]
19+
读取 3 并自动推入数组 -> [1,3]
20+
```
21+
22+
## 代码
23+
#### 方法一
24+
```python
25+
target = [1,3]
26+
# 把目标数组转换为
27+
target = [1,0,3]
28+
# 发现规律
29+
# 只要是0的地方都是先Push,再Pop
30+
# 非0的地方直接Push
31+
```
32+
33+
```python
34+
def buildArray(target, n):
35+
res = []
36+
37+
tmp = [0 for _ in range(target[-1])]
38+
for item in target:
39+
tmp[item-1] = item
40+
41+
for item in tmp:
42+
if item == 0:
43+
res.append('Push')
44+
res.append('Pop')
45+
else:
46+
res.append('Push')
47+
48+
return res
49+
```
50+
51+
#### 方法二:
52+
* 从1到n遍历
53+
* 如果元素在target里面,就是Push
54+
* 如果元素不在,就是先Push,再Pop
55+
56+
```python
57+
def buildArray(target, n):
58+
res = []
59+
for item in range(1, n+1):
60+
if item > target[-1]:
61+
break
62+
63+
if item in target:
64+
res.append('Push')
65+
else:
66+
res.append('Push')
67+
res.append('Pop')
68+
return res
69+
```

0 commit comments

Comments
 (0)