Reputation: 67
I am getting output impossible. but it must be possible. when i check at the editor it shows that that the case is always true i.e last three cases of switch.
public String isPossible(String express) {
char a = ' ';
char b = ' ';
boolean flag = true;
Stack<Character> pile = new Stack<Character>();
char [] array = express.toCharArray();
for (int i = 0 ; i < array.length ; i++) {
a = array[i];
switch (a) {
case '(':
pile.push(a);
break;
case '{':
pile.push(a);
break;
case '[':
pile.push(a);
break;
case ')':
b = pile.pop();
if (b != '(' || b != 'X')
flag = false;
break;
case '}':
b = pile.pop();
if (b != '{' || b != 'X')
flag = false;
break;
case ']':
b = pile.pop();
if (b != ']' || b != 'X')
flag = false;
break;
}
}
if (flag == false || pile.size() % 2 != 0)
return "impossible";
else
return "possible";
}
public static void main(String args[]) {
Merge a = new Merge();
System.out.println(a.isPossible("(())"));
}
Upvotes: 0
Views: 66
Reputation: 178253
Your logic is incorrectly using the ||
(or) operator. It is always true that b
is not '('
or it's not 'X'
. You want &&
(and).
Replace
if(b!='(' || b!= 'X')
with
if(b!='(' && b!= 'X')
and similarly for the other if
conditions in the case statements.
Upvotes: 2