我的代码所做的是在方法countSubstring中传递两个字符串和一个计数。 countSubString计算strOne中strTwo的出现次数。 但我有困难,因为我不明白几件事情:结束字符串,递归和搜索出现
public class CountingSubString
{
int CountSubString(String strOne, String strTwo, int count)
{
int i = 0;
int foundAtIndex = strOne.indexOf(strTwo, i);
if(foundAtIndex == -1)
{
i++;
}
else//(foundAtIndex != -1)
{
count++;
int newStartIndex = foundAtIndex + strTwo.length();
String StringFromString = strOne.substring(newStartIndex, strOne.length()-1);
count = count + countSubString(StringFromString, strTwo, count);
return count;
}
return count;
}
public class TestCountingSubString
{
public static void main(String[] argv)
{
String s2 = new String("abab");
String s3 = new String("ab");
String s4 = new String("aabbaa");
String s5 = new String("aa");
countingSubString CountOfString = new countingSubString();
int count = CountOfString.countSubString(s2, s3, 0);
System.out.println(count);
}
}
问题1)我们考虑这样的情况字符串1 = c和字符串2 = AA。 c不包含aa。 如何为这种情况制定基本案例? 我的尝试:
问题2)在java中,字符串是如何结束的? 如果我有string1 =“aabbaa”,并且string2 =“aa”。 我从索引0和1得到aa,所以我返回索引0.计算string2.length()+ 0 = 2. 现在我在beginIndex:2到endindex:string2.length-1的子串字符串1获取新的字符串获得“bbaa”。 再次搜索,我获得索引2和3的字符串aa。 如何使字符串aa后的递归结束?
能够击败答案我正要给... :) – jamesthollowell 2014-09-19 04:17:33
因为我通过dianel良章中约20递归读一本书编程在Java中,我得到了递归调用,但答案,可以做到这一点更容易 – 2014-09-19 04:23:45
@DavidHang看看这个解决方案是否适合你。如果是的话,接受答案,否则评论。 – Ankush 2014-09-19 05:06:07