我有以下代码
static String super_reduced_string(StringBuilder s){
for(int i=0;i<s.length()-1;i++){
if(s.charAt(i)==s.charAt(i+1)){
StringBuilder s1= s.delete(i,i+2);
//System.out.println("Reduced String is "+s1 +s1.length());
if(s1.length()==0){
System.out.println("Reduced String is"+s1 +s1.length());
return "Empty String";
}
super_reduced_string(s1);
}
}
return s.toString();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.next();
String result = super_reduced_string(new StringBuilder(s));
System.out.println(result);
}
当我将输入作为"aa"传递时,它返回的"空字符串"作为输出,但是当我传递"baab"时,它返回 null 作为输出。我不明白为什么会这样。
有人可以解释一下吗?
您设置了删除重复字母:
if(s.charAt(i)==s.charAt(i+1)){
StringBuilder s1= s.delete(i,i+2);
因此,当您将aa
传递给该方法时,它将删除这两个字母,因为它们是相同的。如果你传递baab
,那么它将删除aa
留下bb
,然后它将删除bb
,因为它们也是重复的。
编辑:
您需要添加一个 return
语句,如果您的if
不执行,该语句将执行:
static String super_reduced_string(StringBuilder s){
for(int i=0;i<s.length()-1;i++){
if(s.charAt(i)==s.charAt(i+1)){
StringBuilder s1= s.delete(i,i+2);
//System.out.println("Reduced String is "+s1 +s1.length());
if(s1.length()==0){
System.out.println("Reduced String is"+s1 +s1.length());
return "Empty String";
}
/*
* Needs a return statement, otherwise it will return the
* empty value below
*/
return super_reduced_string(s1);
}
}
return s.toString();
/*
* If the if statement does not execute,
* and the statement above is missing a
* return declaration, then this will return
* an empty string: ""
*/
}