BAEL-3481 - updated with review comments.

This commit is contained in:
BudBak 2019-12-12 16:31:05 +05:30
parent 8c98046f92
commit 767d74b38d
2 changed files with 22 additions and 40 deletions

View File

@ -5,22 +5,18 @@ 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;
return false;
} else {
char[] ch = str.toCharArray();
for (char c : ch) {
if (!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) {
result = false;
break;
return false;
}
}
}
if(result) {
Stack<Character> stack = new Stack<>();
for (char ch: str.toCharArray()) {
if (ch == '{' || ch == '[' || ch == '(') {
@ -32,16 +28,12 @@ public class BalancedBracketsUsingStack {
|| (stack.peek() == '(' && ch == ')')
)) {
stack.pop();
result = true;
} else {
result = false;
break;
return false;
}
}
}
}
}
return result;
return true;
}
}

View File

@ -3,35 +3,25 @@ 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;
return false;
} else {
char[] ch = str.toCharArray();
for(char c : ch) {
if(!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) {
result = false;
break;
return false;
}
}
}
if (result) {
while (str.indexOf("()") >= 0 || str.indexOf("[]") >= 0 || str.indexOf("{}") >= 0) {
while (str.contains("()") || str.contains("[]") || str.contains("{}")) {
str = str.replaceAll("\\(\\)", "")
.replaceAll("\\[\\]", "")
.replaceAll("\\{\\}", "");
}
if (str.length() > 0) {
result = false;
} else {
result = true;
}
}
return (str.length() == 0);
return result;
}
}