File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed
main/java/s0020.valid.parentheses
test/java/s0020.valid.parentheses Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ package s0020 .valid .parentheses ;
2+
3+ import java .util .Stack ;
4+
5+ public class Solution {
6+ public boolean isValid (String s ) {
7+ Stack <Character > stack = new Stack <Character >();
8+ for (int i = 0 ; i < s .length (); i ++) {
9+ char c = s .charAt (i );
10+ if (c == '(' || c == '[' || c == '{' ) {
11+ stack .push (c );
12+ } else if (c == ')' && !stack .isEmpty () && stack .peek () == '(' ) {
13+ stack .pop ();
14+ } else if (c == '}' && !stack .isEmpty () && stack .peek () == '{' ) {
15+ stack .pop ();
16+ } else if (c == ']' && !stack .isEmpty () && stack .peek () == '[' ) {
17+ stack .pop ();
18+ } else return false ;
19+ }
20+ return stack .isEmpty ();
21+ }
22+ }
Original file line number Diff line number Diff line change 1+ package s0020 .valid .parentheses ;
2+
3+ import static org .hamcrest .CoreMatchers .equalTo ;
4+ import static org .hamcrest .MatcherAssert .assertThat ;
5+
6+ import org .junit .Test ;
7+
8+ public class SolutionTest {
9+ @ Test
10+ public void isValid () {
11+ assertThat (new Solution ().isValid ("()" ), equalTo (true ));
12+ }
13+ }
You can’t perform that action at this time.
0 commit comments