给定一个字符串,递归计算(无循环)字符串中出现小写“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;
}
}
答案 0 :(得分:3)
应使用以下代码:
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);
}
答案 1 :(得分:0)
F(x[1...n]) =
if the string starts with "hi" then 1 + F(x[3...n])
else F(x[2...n])
答案 2 :(得分:0)
您的递归函数需要一个参数,告诉它在字符串中的哪个位置开始查找。如果该位置的字符为'h'
,则检查后面的字符是'i'
;如果是的话,你找到了一个匹配。
对于检查字符串剩余部分的递归调用,如果不是'i'
,则传递下一个字符的索引,如果是,则传递两个字符。
(我只是给出一个描述而不是实际的代码,因为这看起来像是一个家庭作业问题。)
答案 3 :(得分:0)
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));
}
答案 4 :(得分:0)
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;
}
}