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,43 +5,35 @@ import java.util.Stack;
public class BalancedBracketsUsingStack { public class BalancedBracketsUsingStack {
public boolean isBalanced(String str) { public boolean isBalanced(String str) {
boolean result = true;
if (null == str || str.length() == 0 || ((str.length() % 2) != 0)) { if (null == str || str.length() == 0 || ((str.length() % 2) != 0)) {
result = false; return false;
} else { } else {
char[] ch = str.toCharArray(); char[] ch = str.toCharArray();
for (char c : ch) { for (char c : ch) {
if (!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) { if (!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) {
result = false; return false;
break;
} }
} }
} }
if(result) { Stack<Character> stack = new Stack<>();
Stack<Character> stack = new Stack<>(); for (char ch: str.toCharArray()) {
for (char ch: str.toCharArray()) { if (ch == '{' || ch == '[' || ch == '(') {
if (ch == '{' || ch == '[' || ch == '(') { stack.push(ch);
stack.push(ch); } else {
if ( !stack.isEmpty()
&& ((stack.peek() == '{' && ch == '}')
|| (stack.peek() == '[' && ch == ']')
|| (stack.peek() == '(' && ch == ')')
)) {
stack.pop();
} else { } else {
if ( !stack.isEmpty() return false;
&& ((stack.peek() == '{' && ch == '}')
|| (stack.peek() == '[' && ch == ']')
|| (stack.peek() == '(' && ch == ')')
)) {
stack.pop();
result = true;
} else {
result = false;
break;
}
} }
} }
} }
return result; return true;
} }
} }

View File

@ -3,35 +3,25 @@ package com.baeldung.algorithms.balancedbrackets;
public class BalancedBracketsUsingString { public class BalancedBracketsUsingString {
public boolean isBalanced(String str) { public boolean isBalanced(String str) {
boolean result = true;
if (null == str || str.length() == 0 || ((str.length() % 2) != 0)) { if (null == str || str.length() == 0 || ((str.length() % 2) != 0)) {
result = false; return false;
} else { } else {
char[] ch = str.toCharArray(); char[] ch = str.toCharArray();
for(char c : ch) { for(char c : ch) {
if(!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) { if(!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) {
result = false; return false;
break;
} }
} }
} }
if (result) { while (str.contains("()") || str.contains("[]") || str.contains("{}")) {
while (str.indexOf("()") >= 0 || str.indexOf("[]") >= 0 || str.indexOf("{}") >= 0) { str = str.replaceAll("\\(\\)", "")
str = str.replaceAll("\\(\\)", "") .replaceAll("\\[\\]", "")
.replaceAll("\\[\\]", "") .replaceAll("\\{\\}", "");
.replaceAll("\\{\\}", "");
}
if (str.length() > 0) {
result = false;
} else {
result = true;
}
} }
return (str.length() == 0);
return result;
} }
} }