You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/main/java/g0001_0100/s0020_valid_parentheses/readme.md
+53-1Lines changed: 53 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -43,4 +43,56 @@ An input string is valid if:
43
43
**Constraints:**
44
44
45
45
* <code>1 <= s.length <= 10<sup>4</sup></code>
46
-
*`s` consists of parentheses only `'()[]{}'`.
46
+
*`s` consists of parentheses only `'()[]{}'`.
47
+
48
+
To solve the Valid Parentheses problem in Java with a `Solution` class, we'll use a stack data structure. Here are the steps:
49
+
50
+
1. Define a `Solution` class with a method named `isValid` that takes a string `s` as input and returns a boolean indicating whether the string contains valid parentheses.
51
+
2. Create a stack to store opening parentheses.
52
+
3. Iterate through each character in the input string `s`.
53
+
4. If the current character is an opening parenthesis (`'('`, `'{'`, or `'['`), push it onto the stack.
54
+
5. If the current character is a closing parenthesis (`')'`, `'}'`, or `']'`), check if the stack is empty. If it is, return `false` because there's no matching opening parenthesis for the current closing parenthesis.
55
+
6. If the stack is not empty, pop the top element from the stack and check if it matches the current closing parenthesis. If it doesn't match, return `false`.
56
+
7. After iterating through all characters in `s`, check if the stack is empty. If it's not empty, return `false` because there are unmatched opening parentheses remaining.
57
+
8. If the stack is empty after processing all characters, return `true` because all parentheses are valid.
58
+
59
+
Here's the implementation:
60
+
61
+
```java
62
+
importjava.util.Stack;
63
+
64
+
publicclassSolution {
65
+
publicbooleanisValid(Strings) {
66
+
Stack<Character> stack =newStack<>();
67
+
68
+
for (char c : s.toCharArray()) {
69
+
if (c =='('|| c =='{'|| c =='[') {
70
+
stack.push(c);
71
+
} else {
72
+
if (stack.isEmpty()) {
73
+
returnfalse;
74
+
}
75
+
char top = stack.pop();
76
+
if ((c ==')'&& top !='(') || (c =='}'&& top !='{') || (c ==']'&& top !='[')) {
0 commit comments