Skip to content

Commit 04ac9c3

Browse files
add a more concise solution for 20
1 parent e22405b commit 04ac9c3

File tree

1 file changed

+22
-0
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+22
-0
lines changed

src/main/java/com/fishercoder/solutions/_20.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,26 @@ public boolean isValid(String s) {
5959
return stack.isEmpty();
6060
}
6161
}
62+
63+
public static class Solution2 {
64+
/**
65+
* A more concise solution:
66+
* credit: https://leetcode.com/problems/valid-parentheses/discuss/9178/Short-java-solution
67+
* */
68+
public boolean isValid(String s) {
69+
Stack<Character> stack = new Stack<>();
70+
for (char c : s.toCharArray()) {
71+
if (c == '(') {
72+
stack.push(')');
73+
} else if (c == '{') {
74+
stack.push('}');
75+
} else if (c == '[') {
76+
stack.push(']');
77+
} else if (stack.isEmpty() || stack.pop() != c) {
78+
return false;
79+
}
80+
}
81+
return stack.isEmpty();
82+
}
83+
}
6284
}

0 commit comments

Comments
 (0)