BAEL-3481

This commit is contained in:
BudBak
2019-12-03 15:29:04 +05:30
parent ac357ee98c
commit b333276281
4 changed files with 244 additions and 0 deletions
@@ -0,0 +1,47 @@
package com.baeldung.algorithms.balancedbrackets;
import java.util.Stack;
public class BalancedBracketsUsingStack {
public boolean isBalanced(String str) {
boolean result = true;
if (null == str || str.length() == 0 || ((str.length() % 2) != 0)) {
result = false;
} else {
char[] ch = str.toCharArray();
for (char c : ch) {
if (!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) {
result = false;
break;
}
}
}
if(result) {
Stack<Character> stack = new Stack<>();
for (char ch: str.toCharArray()) {
if (ch == '{' || ch == '[' || ch == '(') {
stack.push(ch);
} else {
if ( !stack.isEmpty()
&& ((stack.peek() == '{' && ch == '}')
|| (stack.peek() == '[' && ch == ']')
|| (stack.peek() == '(' && ch == ')')
)) {
stack.pop();
result = true;
} else {
result = false;
break;
}
}
}
}
return result;
}
}
@@ -0,0 +1,37 @@
package com.baeldung.algorithms.balancedbrackets;
public class BalancedBracketsUsingString {
public boolean isBalanced(String str) {
boolean result = true;
if (null == str || str.length() == 0 || ((str.length() % 2) != 0)) {
result = false;
} else {
char[] ch = str.toCharArray();
for(char c : ch) {
if(!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) {
result = false;
break;
}
}
}
if (result) {
while (str.indexOf("()") >= 0 || str.indexOf("[]") >= 0 || str.indexOf("{}") >= 0) {
str = str.replaceAll("\\(\\)", "")
.replaceAll("\\[\\]", "")
.replaceAll("\\{\\}", "");
}
if (str.length() > 0) {
result = false;
} else {
result = true;
}
}
return result;
}
}