BAEL-3481 - updated with review comments.
This commit is contained in:
parent
8c98046f92
commit
767d74b38d
@ -5,43 +5,35 @@ 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 == '(') {
|
||||
stack.push(ch);
|
||||
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();
|
||||
} else {
|
||||
if ( !stack.isEmpty()
|
||||
&& ((stack.peek() == '{' && ch == '}')
|
||||
|| (stack.peek() == '[' && ch == ']')
|
||||
|| (stack.peek() == '(' && ch == ')')
|
||||
)) {
|
||||
stack.pop();
|
||||
result = true;
|
||||
} else {
|
||||
result = false;
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
return true;
|
||||
}
|
||||
}
|
@ -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) {
|
||||
str = str.replaceAll("\\(\\)", "")
|
||||
.replaceAll("\\[\\]", "")
|
||||
.replaceAll("\\{\\}", "");
|
||||
}
|
||||
if (str.length() > 0) {
|
||||
result = false;
|
||||
} else {
|
||||
result = true;
|
||||
}
|
||||
while (str.contains("()") || str.contains("[]") || str.contains("{}")) {
|
||||
str = str.replaceAll("\\(\\)", "")
|
||||
.replaceAll("\\[\\]", "")
|
||||
.replaceAll("\\{\\}", "");
|
||||
}
|
||||
return (str.length() == 0);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user