https://belbesy.wordpress.com/2011/04/16/uva-00673-parentheses-balance/
You are given a string consisting of parentheses () and []. A string of this type is said to be correct:
http://samus250.blogspot.com/2013/09/uva-problem-parenthesis-balance.html
You are given a string consisting of parentheses () and []. A string of this type is said to be correct:
- (a)
- if it is the empty string
- (b)
- if A and B are correct, AB is correct,
- (c)
- if A is correct, (A) and [A] is correct.
Input
The file contains a positive integer n and a sequence of n strings of parentheses () and [], one string a line.Output
A sequence of Yes or No on the output file.Sample Input
3 ([]) (([()]))) ([()[]()])()
Sample Output
Yes No Yes
public
static
void
main(String[] args)
throws
IOException {
BufferedReader bf =
new
BufferedReader(
new
InputStreamReader(System.in));
int
N = Integer.parseInt(bf.readLine());
while
(N-- !=
0
) {
boolean
bad =
false
;
char
[] cs = bf.readLine().toCharArray();
Stack<Character> stk =
new
Stack<Character>();
for
(
char
c : cs) {
if
(c ==
'['
|| c ==
'('
) {
stk.push(c);
}
else
{
if
(c ==
']'
) {
if
(stk.isEmpty() || stk.peek() ==
'('
) bad |=
true
;
}
else
if
(c ==
')'
) {
if
(stk.isEmpty() || stk.peek() ==
'['
) bad |=
true
;
}
if
(!stk.isEmpty()) stk.pop();
}
}
if
(!stk.isEmpty()) bad =
true
;
System.out.println(bad ?
"No"
:
"Yes"
);
}
}
public
static
boolean
solve(String line) {
Stack<Character> stack =
new
Stack<Character>();
for
(
int
i =
0
; i < line.length(); i++) {
char
c = line.charAt(i);
if
(isOpening(c)) {
// Push opening char to stack.
stack.push(c);
}
else
{
// Verify closing parenthesis.
if
(stack.isEmpty()) {
return
false
;
}
else
{
char
cInStack = stack.pop();
if
(map(cInStack) != c) {
return
false
;
}
}
}
}
return
stack.isEmpty();
}
/**
* Returns whether a given char is an opening char.
* @param c The char to classify.
* @return True if it is an opening char, false otherwise.
*/
public
static
boolean
isOpening(
char
c) {
switch
(c) {
case
'('
:
case
'['
:
return
true
;
default
:
return
false
;
}
}
/**
* Maps opening chars to closing chars.
* @param c The opening char.
* @return The corresponding closing char.
*/
public
static
char
map(
char
c) {
switch
(c) {
case
'('
:
return
')'
;
case
'['
:
return
']'
;
default
:
return
' '
;
}
}