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

Commit4cc2604

Browse files
edit 20
1 parentf38309d commit4cc2604

File tree

1 file changed

+17
-15
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+17
-15
lines changed
Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,30 @@
11
packagecom.fishercoder.solutions;
22

3-
importjava.util.Stack;
3+
importjava.util.ArrayDeque;
4+
importjava.util.Deque;
45

5-
/**Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
6-
7-
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.*/
6+
/**
7+
* 20. Valid Parentheses
8+
*
9+
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
10+
* The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.*/
811
publicclass_20 {
912

1013
publicbooleanisValid(Strings) {
11-
Stack<Character>stack =newStack();
12-
char[]schar =s.toCharArray();
13-
for(inti =0;i <schar.length;i++){
14-
if(schar[i] =='(' ||schar[i] =='[' ||schar[i] =='{')stack.push(schar[i]);
15-
elseif(schar[i] ==')' ||schar[i] ==']' ||schar[i] =='}'){
16-
if(stack.isEmpty())returnfalse;
14+
Deque<Character>stack =newArrayDeque<>();
15+
for (inti =0;i <s.length();i++) {
16+
if (s.charAt(i) =='(' ||s.charAt(i) =='{' ||s.charAt(i) =='['){
17+
stack.push(s.charAt(i));
18+
}else {
19+
if(stack.isEmpty())returnfalse;
1720
else {
18-
charpop =stack.pop();
19-
if(schar[i] ==')' &&pop !='(')returnfalse;
20-
elseif(schar[i] ==']' &&pop !='[')returnfalse;
21-
elseif(schar[i] =='}' &&pop !='{')returnfalse;
21+
if (stack.peek() =='(' &&s.charAt(i) !=')')returnfalse;
22+
elseif (stack.peek() =='{' &&s.charAt(i) !='}')returnfalse;
23+
elseif (stack.peek() =='[' &&s.charAt(i) !=']')returnfalse;
24+
stack.pop();
2225
}
2326
}
2427
}
2528
returnstack.isEmpty();
2629
}
27-
2830
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp