FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/Week_01/id_104/LeetCode_20_104.java at master · feixiangcode/algorithm · GitHub
feixiangcode
/
algorithm
Public
forked from
algorithm001/algorithm
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
Week_01
/
id_104
/
LeetCode_20_104.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
69 lines (63 loc) · 1.92 KB
Breadcrumbs
algorithm
/
Week_01
/
id_104
/
LeetCode_20_104.java
Copy path
File metadata and controls
69 lines (63 loc) · 1.92 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
58
59
60
61
62
63
64
65
66
67
68
69
class
Solution
{
private
Map
<
Character
,
Character
>
charMap
=
new
HashMap
();
public
boolean
isValid
(
String
s
) {
//1.拆成数组
//2.从头遍历数组 往栈里插入
//3.记录最后一个入栈的字符 和 当前入栈的字符 比较是否可以消除
// 3.1 可以消除 出栈
// 3.2 不可以消除 继续入栈 记录当前入栈字符为最后一次入栈字符
//4.数组遍历结束后 检查栈的长度是否为0 为0则true 否则false
// 使用栈的数据结构 先入后出
//3.
if
(
s
==
null
){
return
false
;
}
if
(
""
.
equals
(
s
)){
return
true
;
}
initMap
(
charMap
);
Stack
stack
=
new
Stack
();
char
stackTopStr
;
char
str
;
for
(
int
i
=
0
;
i
<
s
.
length
();
i
++){
str
=
s
.
charAt
(
i
);
//获取栈顶元素
if
(
stack
.
empty
()){
//设置默认值
stackTopStr
=
'#'
;
}
else
{
stackTopStr
=(
char
)
stack
.
peek
();
}
//比较栈顶元素是否可消除
if
(
canPop
(
charMap
,
stackTopStr
,
str
)){
stack
.
pop
();
}
else
{
//元素入栈
stack
.
push
(
str
);
}
}
return
stack
.
empty
();
}
/**
* 初始化map
**/
private
void
initMap
(
Map
<
Character
,
Character
>
map
){
map
.
put
(
'('
,
')'
);
map
.
put
(
'{'
,
'}'
);
map
.
put
(
'['
,
']'
);
map
.
put
(
'"'
,
'"'
);
}
/**
* 是否可从栈中移除
* stackTopStr 栈顶元素
* waitInStackStr 即将入栈元素
**/
private
boolean
canPop
(
Map
<
Character
,
Character
>
map
,
char
stackTopStr
,
char
waitInStackStr
){
boolean
pop
=
false
;
Character
v
=
map
.
get
(
stackTopStr
);
if
(
v
!=
null
){
pop
=(
v
==
waitInStackStr
);
}
return
pop
;
}
}
Back
|
FazBrowse Home
|
New Git URL