I am having problems with a newbie in java (and generally programming) with the task that we were given. The assignment is divided into 3 parts to check whether a given line has balanced brackets.
The "rules" are as follows:
"abcdefksdhgs" - balanced"[{aaa<bb>dd}]<232>" - balanced"[ff{<gg}]<ttt>"- NOT balanced (no close for < )"{<}>" - NOT balanced
The first part of the task was to write a method that gets a char array containing a string and finds a FIRST index (= array cell) containing a bracket, one of the following:
} , { , ] , [ , ( , ) , > , <
This, of course, was easily done:
public static int bracketIndex(String str1){
int index = -1;
int i = 0;
for( i = 0; i < str1.length(); i++ ){
if(str1.charAt(i) == '}' || str1.charAt(i) == '{' || str1.charAt(i) == ']' || str1.charAt(i) == '[' || str1.charAt(i) == '(' || str1.charAt(i) == ')' || str1.charAt(i) == '>' || str1.charAt(i) == '<'){
return index = i;
}
}
return index;
}
, , , true, char char (: 1st = '<' 2nd = ' > '= true ( false!), 1st ='<'2nd =' e '= false). :
public static boolean checkBracket(char firstChar, char secondChar){
if ( (firstChar == '(') && (secondChar == ')') ||
(firstChar == '[') && (secondChar == ']') ||
(firstChar == '{') && (secondChar == '}') ||
(firstChar == '<') && (secondChar == '>') ){
return true;
}
return false;
}
- RECURSIVE, , "true",
, . , 1- 2- , , :
: , 2
. :
, false.
, 26 :
public static boolean checkBalance(String str1){
boolean ans;
int a = bracketIndex(str1);
if ( a == -1 ){
return ans = true;
}
if( str1.charAt(a) == '{' ||
str1.charAt(a) == '[' ||
str1.charAt(a) == '<' ||
str1.charAt(a) == '(' ){
int b = bracketIndex(str1.substring(a))+1 ;
if( b != 0 ){
if( checkBracket ( str1.charAt(a), str1.charAt(b) ) == true ){
return ans = true;
}
if( str1.charAt(b) == '{' ||
str1.charAt(b) == '[' ||
str1.charAt(b) == '<' ||
str1.charAt(b) == '(' ){
checkBalance(str1.substring(b-1));
}
else{
return ans = false;
}
}
}
return ans = false;
}
, , 26 true.
, , .