I need to check if given String is balanced or not. This is similar task like that one with balanced parenthesis.
Please let me know if this is understand for you.
CodePudding user response:
try this
public class CheckBalance {
public static void main(String[] args) {
System.out.println(check("asdfgh()hgfdsa"));
}
static boolean isClosing(char first, char sec)
{
if (first == '(' && sec == ')') {
return true;
} else if (first == '{' && sec == '}' ) {
return true;
} else if (first == '[' && sec == ']') {
return true;
}//add other the different Chars
else if(first == sec){
return true;
}
return false;
}
static boolean check(String value) {
if (value != null) {
char[] valueAsArray = value.toCharArray();
int size = valueAsArray.length;
if (size == 0) {
return true;
} else if (size == 1) {
return true;
} else {
for (int i = 0; i < size; i ) {
if (!isClosing(valueAsArray[i], valueAsArray[size - (i 1)])){
return false;
}
if (i == (size-1)/2) {
break;
}
}
return true;
}
} else {
return true;
}
}
}
CodePudding user response:
public boolean isBalanced(String s) {
return isBalanced(s, 0, new LinkedList<>());
}
private boolean isBalanced(String s, int index, LinkedList<Character> stack) {
if (index >= s.length())
return stack.isEmpty();
char c = s.charAt(index);
if (!stack.isEmpty() && Character.compare(c, stack.getLast()) == 0) {
stack.removeLast();
if (isBalanced(s, index 1, stack))
return true;
stack.add(c);
}
stack.add(c);
return isBalanced(s, index 1, stack);
}
CodePudding user response:
ABAB is wrong right ? it is the same with parenthesis ?