-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
58 lines (57 loc) · 1.55 KB
/
Copy pathsolution.java
File metadata and controls
58 lines (57 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// 20. Valid Parentheses
// https://leetcode.com/problems/valid-parentheses/
// Easy | Java | Accepted 2025-10-26
// Runtime 9 ms | Memory 45.6 MB
class Solution {
public boolean isValid(String s) {
Stack<String> stack = new Stack<>();
for(int i = 0 ; i<s.length(); i++)
{
if(s.substring(i,i+1).equals(")"))
{
if(stack.isEmpty())
{
return false;
}
String c = stack.pop();
if(!c.equals("("))
{
return false;
}
}
if(s.substring(i,i+1).equals("]"))
{
if(stack.isEmpty())
{
return false;
}
String c = stack.pop();
if(!c.equals("["))
{
return false;
}
}
if(s.substring(i,i+1).equals("}"))
{
if(stack.isEmpty())
{
return false;
}
String c = stack.pop();
if(!c.equals("{"))
{
return false;
}
}
else if(s.substring(i,i+1).equals("(")||s.substring(i,i+1).equals("[")||s.substring(i,i+1).equals("{"))
{
stack.push(s.substring(i,i+1));
}
}
if(!stack.isEmpty())
{
return false;
}
return true;
}
}