我作为一个新手在Java(和编程的所有)与赋予给我们的任务麻烦。分配分为3部分,以检查给定字符串是否有平衡括号。检查一个给定的字符串是否平衡括号字符串,递归地
的 “规则” 如下:
"abcdefksdhgs"
- 平衡"[{aaa<bb>dd}]<232>"
- 平衡"[ff{<gg}]<ttt>"
- 不均衡(不封闭的 '<')"{<}>"
- 不平衡
分配的第一部分是写,将得到字符数组包含字符串, 并且将找到的第一个索引包含托架(=阵列单元),执行以下操作之一的方法:
} , { , ] , [ , (,) , > , <
当然,这是很容易做到:
/**
* bracketIndex - 1st Method:
* this method will get a single string (read from the text file),
* and will find the first index char that is any bracket of the following: },{,],[,(,),>,<
* @param str1 - the given string.
* @return index - the first index that contains character that is one of the brackets listed above.
*/
public static int bracketIndex(String str1){
int index = -1; // default value: didn't find any bracket in the string.
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;
}//if
}//for
return index;
}//end of bracketIndex
第二部分是写将得到两个字符,并返回true的方法只有当第二个字符是第一个字符的适当的右括号(例如:1 ='<'2nd ='>'= true(相反是假!),1st ='<'2nd = 'e'= false)。这也没有问题:
/**
* checkBracket - 2nd Method:
*
* @param firstChar, secondChar - two chars.
* @return True - if the the two chars are brackets, in which the second char is the closing bracket of the first char
*/
public static boolean checkBracket(char firstChar, char secondChar){
if ( (firstChar == '(') && (secondChar == ')') ||
(firstChar == '[') && (secondChar == ']') ||
(firstChar == '{') && (secondChar == '}') ||
(firstChar == '<') && (secondChar == '>') ){
return true;
}//if
return false;
}//end of checkBracket
第三部分是写一个递归方法,会得到一个字符串,并将返回“真” 当且仅当该字符串是平衡支架字符串。当然,我们需要使用我们已经写1 &第二方法,也是我们得到一个提示:
提示:使用的辅助方法,将得到2串
在这部分我米卡住了。我想出了几个停车情况:
- 如果没有括号都在给定的字符串 - 返回true
- 如果给定的字符串为空,则返回true(这个选项被覆盖在第一方法)
- 如果找到打开支架,以及匹配闭架 - 返回true
否则,返回false。在代码 写作本身,我目前卡住,不知道如何从递归调用继续行26在我的代码这种方法:
/**
* checkBalance - 3rd Method:
* will check if a given string is a balanced string.
* @param str1 - the given string to check.
* @return true - if the given string is balanced, false - if the given string isn't balanced.
*/
public static boolean checkBalance(String str1){
boolean ans;
int a = bracketIndex(str1);
if (a == -1){
return ans = true;
}//if
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
if(str1.charAt(b) == '{' ||
str1.charAt(b) == '[' ||
str1.charAt(b) == '<' ||
str1.charAt(b) == '(' ){
checkBalance(str1.substring(b-1));
}//if
else{
return ans = false;
}//else
}//if
}//if
return ans = false;
}//end of checkBalance
我不知道该怎么继续,如果来自第26行的递归代码将返回true。
我很乐意从这里的专家那里得到一些指导,告诉我要走向哪个方向,或者我从一开始就做错了一切。
我想你还没有理解提示。它是说,接受一个参数并返回一个布尔值的主函数本身不需要递归,而是它应该有一个递归辅助函数,它需要两个字符串(并且返回任何便于实现的辅助函数,可能是整数索引或其他字符串)。 – Blckknght