-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathValid_Parentheses.java
More file actions
68 lines (61 loc) · 2.96 KB
/
Valid_Parentheses.java
File metadata and controls
68 lines (61 loc) · 2.96 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
59
60
61
62
63
64
65
66
67
68
// Github username: Priyangshu1711
// Aim: To check if any the given String with parentheses, has valid parentheses or not .
//Data Structure Used: ~STACK~
//Time complexity: O(n)
//Space complexity: O(n)
// Date: 08/10/2022
// **************************************************************** //
import java.util.Stack;// to use the Stack class from the util package.
import java.util.Scanner;
class Valid_Parentheses {
public boolean isValid(String s) {
// creating object for the Stack class. here st.
Stack<String> st = new Stack<String>();
// making a character array of the string.
for (char c : s.toCharArray()){
String cc = String.valueOf(c);
// to check if the parantheis begun.
if(c=='{'|| c=='['|| c =='('){
st.push(cc);
}
else{
// if the input is empty then returns false.
if(st.empty())return false;
char top = st.peek().toCharArray()[0];
//if the input has any other chatacters except parantheses then ignores and continues.
if(c!='{' && c!='[' && c !='(' && c != '}' && c!= ']' && c!= ')' ){
continue;
}
// to check if the parentheses is closed respectively *
if((top == '{' && c == '}') ||
(top == '[' && c== ']') ||
(top == '(' && c== ')')){
// * if yes then we will go on popping it from stack until its empty.
st.pop() ;
}
// if the algorithm couldn't remove all the parentheses from the stack then returns false *
else return false;
}
}
// * but if it could remove all the parentheses from the stack then returns true.
return st.empty();
}
// the main function
public static void main(String ...args ){
//creating object for the Valid_Parentheses class
Valid_Parentheses obj = new Valid_Parentheses();
System.out.println("enter a valid string with parentheses eg-[{[helloworld])}] : ");
try (Scanner sc = new Scanner (System.in)) {
// taking the returned boolean value in flag.
boolean flag = obj.isValid(sc.nextLine());
// if the flag was flase then prints false *
if(flag==true){
System.out.println("True");
}
// *else true.
else{
System.out.println("False");}
}
}
}
// **************************************************************** //