-
-
Notifications
You must be signed in to change notification settings - Fork 51
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
balance parenthesis: check given string is balanced or not having par…
…enthesis
- Loading branch information
1 parent
9a312dd
commit 2fd81d7
Showing
1 changed file
with
101 additions
and
0 deletions.
There are no files selected for viewing
101 changes: 101 additions & 0 deletions
101
CodingBlocks Training/Day17/balancedString_paranthesis.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
package Lecture17; | ||
|
||
import java.util.Stack; | ||
|
||
public class balancedString_paranthesis { | ||
|
||
public static void main(String[] args) { | ||
|
||
String str = "{([a+b]+[c+d])}"; | ||
|
||
System.out.println(isBalanced(str)); | ||
|
||
System.out.println(isBalanced("")); // case 0 | ||
System.out.println(isBalanced("[a+b")); | ||
System.out.println(isBalanced("a+b)])")); // case 2.1 | ||
System.out.println(isBalanced("a+b+c+d*e-e")); // case 3 | ||
System.out.println(isBalanced("{[a+b]}")); | ||
} | ||
|
||
public static boolean isBalanced(String str) { | ||
|
||
// case 0 | ||
if (str.equals("")) { | ||
return false; | ||
} | ||
Stack<Character> stack = new Stack<Character>(); | ||
|
||
int notParanthesiscount = 0; | ||
|
||
for (int index = 0; index < str.length(); index++) { | ||
|
||
char cc = str.charAt(index); | ||
|
||
// case 1 | ||
if (cc == '{' || cc == '[' || cc == '(') { | ||
stack.push(cc); | ||
} | ||
|
||
// case 2 | ||
else if (cc == '}' || cc == ']' || cc == ')') { | ||
|
||
// case 2.1 | ||
if (stack.isEmpty()) { | ||
return false; | ||
} | ||
|
||
char top = stack.peek(); | ||
|
||
// case 2.2 | ||
if (cc == ']') { | ||
if (top == '[') { | ||
return true; | ||
} else { | ||
return false; | ||
} | ||
|
||
// case 2.3 | ||
} else if (cc == '}') { | ||
if (top == '{') { | ||
return true; | ||
} else { | ||
return false; | ||
} | ||
} | ||
|
||
// case 2.4 | ||
else if (cc == ')') { | ||
if (top == '(') { | ||
return true; | ||
} else { | ||
return false; | ||
} | ||
} | ||
|
||
} | ||
|
||
// case 3 | ||
else { | ||
// do nothing for any other character in string rather than | ||
// parenthesis | ||
notParanthesiscount++; | ||
} | ||
} | ||
if (stack.isEmpty() && notParanthesiscount != str.length()) { | ||
return true; | ||
} else { | ||
return false; | ||
} | ||
} | ||
|
||
} | ||
|
||
|
||
/* output | ||
true | ||
false | ||
false | ||
false | ||
false | ||
true | ||
*/ |