forked from frigid-lynx/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidParenthesis.java
56 lines (47 loc) · 1.4 KB
/
validParenthesis.java
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
/*
Given a string s, containing just the characters '(',')','[',']','{','}', determine if
the input string is valid.
An input string is valid if:
* Open brackets must be closed by the same type of brackets.
*open brackets must be closed in correct order.
Example:
Input: str = "{()}"
Output: true;
Input: str = "{]"
Output: false;
Input: "{()"
Output: false;
*/
package Stacks;
import java.util.Scanner;
import java.util.Stack;
public class validParenthesis {
public boolean isValid(String str){
Stack<Character> stack = new Stack<>();
for(char c : str.toCharArray()){
if(c == '{' || c == '[' || c == '('){
stack.push(c);
}else{
if(stack.isEmpty()){
return false;
}else{
char top = stack.peek();
if(c == '}' && top == '{' ||
c == ')' && top =='(' ||
c == ']' && top == '['){
stack.pop();
}else{
return false;
}
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
validParenthesis stack = new validParenthesis();
String str = sc.nextLine();
System.out.println(stack.isValid(str));
}
}