Skip to content

Commit 4cc2604

Browse files
edit 20
1 parent f38309d commit 4cc2604

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
package com.fishercoder.solutions;
22

3-
import java.util.Stack;
3+
import java.util.ArrayDeque;
4+
import java.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
public class _20 {
912

1013
public boolean isValid(String s) {
11-
Stack<Character> stack = new Stack();
12-
char[] schar = s.toCharArray();
13-
for(int i = 0; i < schar.length; i++){
14-
if(schar[i] == '(' || schar[i] == '[' || schar[i] == '{') stack.push(schar[i]);
15-
else if(schar[i] == ')' || schar[i] == ']' || schar[i] == '}'){
16-
if(stack.isEmpty()) return false;
14+
Deque<Character> stack = new ArrayDeque<>();
15+
for (int i = 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()) return false;
1720
else {
18-
char pop = stack.pop();
19-
if(schar[i] == ')' && pop != '(') return false;
20-
else if(schar[i] == ']' && pop != '[') return false;
21-
else if(schar[i] == '}' && pop != '{') return false;
21+
if (stack.peek() == '(' && s.charAt(i) != ')') return false;
22+
else if (stack.peek() == '{' && s.charAt(i) != '}') return false;
23+
else if (stack.peek() == '[' && s.charAt(i) != ']') return false;
24+
stack.pop();
2225
}
2326
}
2427
}
2528
return stack.isEmpty();
2629
}
27-
2830
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy