给定一个字符串,递归地(没有循环)计算
如果给定字符串,递归地计算(不循环)的小写的“hi”的次数出现在字符串中给定一个字符串,递归地(没有循环)计算
countHi(“xxhixx”) - > 1
countHi( “xhixhixx”) - > 2
countHi( “HI”) - > 1
public class Tester {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int count = countHi("xxhixx");
System.out.println("countHi: " + count);
}
public static int countHi(String s) {
if (s.length() == 0) {
return 0;
}
int spot = s.indexOf("hi");
if(spot > 0)
{
String nextString = s.substring(spot + 2);
return 1 + countHi(nextString);
}
return 1;
}
}
F(x[1...n]) =
if the string starts with "hi" then 1 + F(x[3...n])
else F(x[2...n])
应具有下列工作代码:
public static int countHi(String s) {
return countHi(s, 0);
}
public static int countHi(String s, int pos) {
if (s.length() - pos < 2) {
return 0;
}
int result = 0;
if(s.charAt(pos) == 'h' && s.charAt(pos + 1) == 'i') {
result++;
}
return result + countHi(s, pos + 2);
}
。更新的代码,而无需子,好像他们是一个字符数组 – MasterCassim
字符串不能被索引你可以用'的charAt()',或者转换成使用'toCharArray()' –
由于字符数组;更新了我的答案。 – MasterCassim
您的递归函数将需要一个参数,告诉它在字符串开始查找的位置。如果该位置的字符是'h'
,则检查后面的字符是否为'i'
;如果是,你找到了一个匹配。
对于检查字符串的其余部分的递归调用,如果不是'i'
,则传递下一个字符的索引,如果是,则传递前面的两个字符。
(我给刚一说明,而不是实际的代码,因为这看起来像一个家庭作业的问题。)
public static int recCountHi(String str) {
if(str.length() < 2) {
return 0;
}
if(str.substring(0, 2).equals("hi")) {
return 1 + recCountHi(str.substring(1));
}
return recCountHi(str.substring(1));
}
package com.indivunet.utils;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class Tester
{
/**
* @param args
*/
public static void main(String[] args)
{
printCountFor("xxhixx", 1);
printCountFor("", 0);
printCountFor("xxhixxhihi", 3);
printCountFor(null, 0);
}
@Test
public void countHi()
{
assertAndPrint("xxhixx", 1);
assertAndPrint("", 0);
assertAndPrint("xxhixxhihi", 3);
assertAndPrint(null, 0);
}
private void assertAndPrint(String string, int expectedCount)
{
int count = printCountFor(string, expectedCount);
assertEquals(expectedCount, count);
}
private static int printCountFor(String string, int expected)
{
int count = countHi(string);
System.out.println("string: \"" + string + "\" expected: " + expected + " count: " + count);
return count;
}
public static int countHi(String s)
{
if (s == null)
{
return 0;
}
int count = 0;
boolean hiSpotted = true;
while (hiSpotted)
{
int startOfNextHi = s.indexOf("hi");
hiSpotted = startOfNextHi >= 0;
if (!hiSpotted)
{
return count;
}
s = s.substring(startOfNextHi + 2);
count++;
}
return count;
}
}
而且你的问题是什么? –
'indexOf'使用循环。 –
问题是什么?我假设soem输入会返回一个太大的数字?您不会考虑大于0的字符串,但根本不包含“hi”。你的方法将返回1它shoudl返回0,您可以删除德支票长度== 0,而是区分(现货> = 0) - >递归调用+ 1和(现货返回0 –