Problem:
Given a string, compute recursively (no loops) the number of times lowercase "hi" appears in the string.
countHi("xxhixx") → 1
countHi("xhixhix") → 2
countHi("hi") → 1
Solution:
public int countHi(String str) { if (str.length() < 2) return 0; if (str.substring(0,2).equals("hi")) return 1 + countHi(str.substring(1)); else return countHi(str.substring(1)); }
public int countHi(String str)
ReplyDelete{
int count = 0;
for(int i = 0; i< str.length() -1; i++)
{
if(str.substring(i,i+2).equals("hi"))
count++;
}
return count;
}
It said no loops...why do you have a for loop?
DeleteDumbass needs to learn how to use a fucking loop
DeleteActually he needs to learn how to read directions
Deletedont call him that
DeleteThis is my solution. I just changed the if condition
ReplyDeletepublic int countHi(String str) {
if(str.length()==0) return 0;
if(str.length()>=2){
if(str.substring(0,2).equalsIgnoreCase("hi")) {
return 1+countHi(str.substring(2));
}
}
return countHi(str.substring(1));
}
public int countHi(String str) {
ReplyDeleteif (str.length()<2)
return 0;
int count = (str.substring(0,2).equals("hi")) ? 1 : 0;
return count + countHi(str.substring(1));
}
ReplyDeletepublic int countHi(String str) {
if( str.length() < 2)
return 0;
String sub = "hi";
if(str.substring(0,2).equals(sub))
return 1 + countHi(str.substring(1));
return countHi(str.substring(1));
}
public int countHi(String str) {
ReplyDeleteif (str.length() == 0) return 0;
if (str.length() >= 2 && str.charAt(0) == 'h' && str.charAt(1) == 'i')
return 1 + countHi(str.substring(2));
else return countHi(str.substring(1));
}