-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathBalancedParentheses.java
72 lines (66 loc) · 1.71 KB
/
BalancedParentheses.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.java.parentheses;
import java.util.ArrayList;
import java.util.Scanner;
/*
* Find whether the given string is balanced brackets or not
* Possible brackets are ( ) { } [ ]
*
* Balanced Brackets means
* Each opening brackets has a corresponding closing brackets
* and pairs of brackets are properly nested.
*
* ()[] - VALID
* ([]) - VALID
* ([)] - INVALID
*
*/
public class BalancedParentheses {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any string value :: ");
String str = scanner.nextLine();
String output = isBalanced(str);
System.out.println("Is Balanced Parentheses :: "+output);
scanner.close();
}
public static String isBalanced(String line){
String output = null;
ArrayList<Character> charStack = new ArrayList<>();
for(Character c : line.toCharArray()){
if(c == '(' || c == '[' || c == '{'){
charStack.add(c);
}else{
if(charStack.isEmpty()){
output = "NO";
break;
}
char ch = charStack.remove(charStack.size()-1);
if(c == ')' && ch == '('){
continue;
}else if(c == '}' && ch == '{'){
continue;
}else if(c == ']' && ch == '['){
continue;
}else{
output = "NO";
break;
}
}
}
if(!charStack.isEmpty())
output = "NO";
if(output == null)
output = "YES";
return output;
}
}
/*
INPUT
{[()]}
{[(])}
{{[[(())]]}}
OUTPUT
YES
NO
YES
*/