-
Notifications
You must be signed in to change notification settings - Fork 6
/
ValidateBalancedParentheses.java
73 lines (66 loc) · 1.94 KB
/
ValidateBalancedParentheses.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
73
package com.dailyinterviewprojava.uber;
import java.util.Scanner;
import java.util.Stack;
/**
*
* @author ema
* Validate Balanced Parentheses
*
* Imagine you are building a compiler. Before running any code, the compiler must check that the parentheses in the program are balanced. Every opening bracket must have a corresponding closing bracket. We can approximate this using strings.
*
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
* An input string is valid if:
* - Open brackets are closed by the same type of brackets.
* - Open brackets are closed in the correct order.
* - Note that an empty string is also considered valid.
*
* Example:
* Input: "((()))"
* Output: True
*
* Input: "[()]{}"
* Output: True
*
* Input: "({[)]"
* Output: False
*
*/
public class ValidateBalancedParentheses
{
public static void main( String[] args )
{
// Input to character array
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
char[] characters = input.toCharArray();
System.out.println(isValid(characters));
scanner.close();
}
static boolean isValid(char[] characters) {
// Check if character length is even
if(characters.length % 2 != 0) {
return false;
}
// Validate balanced parentheses
Stack<Character> charStack = new Stack<>();
for(char character : characters) {
switch(character) {
case '{':
charStack.push('}');
break;
case '[':
charStack.push(']');
break;
case '(':
charStack.push(')');
break;
default:
if(charStack.empty() || character != charStack.peek()) {
return false;
}
charStack.pop();
}
}
return charStack.isEmpty();
}
}