NEEDS TO BUILD AND RUN PLEASE USING JAVA Given a string, compute recursively (no
ID: 3729179 • Letter: N
Question
NEEDS TO BUILD AND RUN PLEASE USING JAVA
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 public static int countHi(String str) Given a string, compute recursively the number of times lowercase "hi" appears in the string, however do not count "hi" that have an 'x' immedately before them. countHi2("ahíxhi") 1 countHi2("ahibhi") 2 countHi2("xhixhi") 0 public static int countHi2(String str) Given a string, return recursively a "cleaned" String where adjacent chars that are the same have been reduced to a single char. so "yyzzza yields yza stringClean("yyzzza")--> "yza stringClean("abbbcdd")-->"abcd" stringClean("hello")->"helo" public static String strinClean(String str)Explanation / Answer
// Note: One question at a time please -- Policy of Chegg
class Main {
public static int countHi(String str){
if(str.length() == 1)
return 0;
// hi is found
if(str.charAt(0)=='h' && str.charAt(1) == 'i')
{
// if more characters are there, then skipping these two letters and calling
if(str.length() > 2)
return 1 + countHi(str.substring(2, str.length()));
// else it is the last occurrence of hi. So, returning 1
else
return 1;
}
// not hi, so continuing with rest of the string
return 0 + countHi(str.substring(1, str.length()));
}
public static void main(String[] args) {
System.out.println(countHi("xxhixx"));
System.out.println(countHi("xhixhix"));
System.out.println(countHi("hi"));
}
}
/*
SAMPLE OUTPUT
1
2
1
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.