Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit7fe6d0d

Browse files
committed
valid
1 parent45b9d4d commit7fe6d0d

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

‎string/IsValid.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
packageAlgorithms.string;
2+
3+
importjava.util.Stack;
4+
5+
publicclassIsValid {
6+
publicbooleanisValid(Strings) {
7+
if (s ==null ||s.length() ==0) {
8+
returntrue;
9+
}
10+
11+
Stack<Character>stack =newStack<Character>();
12+
intlen =s.length();
13+
for (inti =0;i <len;i++) {
14+
charc =s.charAt(i);
15+
if (stack.isEmpty()) {
16+
// 栈为空的时候,不能放右括号
17+
if (c ==']' ||c ==')' ||c =='}') {
18+
returnfalse;
19+
}
20+
stack.push(c);
21+
continue;
22+
}
23+
24+
// 栈不为空时,必须 要对应弹出相对应的括号
25+
if (c ==')' &&stack.peek() =='('
26+
||c ==']' &&stack.peek() =='['
27+
||c =='}' &&stack.peek() =='{'
28+
) {
29+
stack.pop();
30+
// 或者继续压入左括号
31+
}elseif (c =='(' ||c =='[' ||c =='{') {
32+
stack.push(c);
33+
// 否则错误退出
34+
}else {
35+
returnfalse;
36+
}
37+
}
38+
39+
returnstack.isEmpty();
40+
}
41+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp