/** * Counts the number of times that one string occurs as a substring in * anot
ID: 3725442 • Letter: #
Question
/** * Counts the number of times that one string occurs as a substring in * another, optionally allowing the occurrences to overlap. For * example: * <ul> * <li><code>countOccurrences("aa", "aaaaa", false)</code> returns 2 * <li><code>countOccurrences("aa", "aaaaa", true)</code> returns 4 * <li><code>countOccurrences("aa", "ababab", true)</code> returns 0 * </ul> * * @param t * string we are looking for ("target") * @param s * string in which we are looking ("source") * @param allowOverlap * true if occurrences of t are allowed to overlap * @return * number of times t occurs in s as a substring */ public static int countOccurrences(String t, String s, boolean allowOverlap) { // TODO return 0; }
Explanation / Answer
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Surya
*/
public class test {
//method that finds... Counts the number of times that one string occurs as a substring in
// another, optionally allowing the occurrences to overlap.
public static int countOccurrences(String t, String s, boolean allowOverlap)
{
// TODO
int n=s.length(),c=0;
int m=t.length(),k,i,j;
// System.out.println(m);
for(i=0;i<n-m+1;)
{
k=i;
for(j=0;j<m;j++)
{
if(s.charAt(k)!=t.charAt(j))//if not matches then breaking..
{
break;
}
k++;
}
if(j==m)//then substring found...
c++;
if(allowOverlap)//if overlapping is allowed then
i++;
else//if overlapping not allowed then
i=i+m;
}
return c;//returning the count...
}
public static void main(String argv[])
{
System.out.println(countOccurrences("aa","aaaaa",false));
System.out.println(countOccurrences("aa","aaaaa",true));
System.out.println(countOccurrences("aa","ababab",true));
}
}
output:
run:
2
4
0
BUILD SUCCESSFUL (total time: 2 seconds)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.