i got the following problem in job interview but couldn't solve it till the end :
you have string "kake" and string "echo"
you have function create( int n) and returns the following:
if n equals 0
output “kake”
if n equals 1
output “echo”
if n greater than 1
output create(n-1) concatenated with create(n-2)
then use this method in another method that takes n and substring
then it finds the number the substring occured in create(n)
the problem is up to n= 35 i have no problems
it is when i try n =40 or 50 i get a out of memory exception and it can't be resolved by increasing memory it seems that ineed to change the algorithm
here's my code :
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Kloc
{
public static String kw(int n)
{
if (n == 0)
return "kake";
if (n == 1)
return "echo";
String n0 = "kake";
String n1 = "echo";
String newN = "";
for ( int i = 2; i<=n;i++)
{
newN = n1 + n0;
n0 = n1;
n1 = newN;
System.gc();
}
return newN;
}
public static void subOccurence(int n, String sub)
{
long occurences = 0;
String kws = kw(n);
int kwLen = kws.length();
int subLen = sub.length();
char subFirstLetter = sub.charAt(0);
for (int i=0; i<=kwLen-subLen;i++)
{
if(kws.charAt(i) == subFirstLetter)
{
boolean occurence = true;
for (int j =0 ; j< subLen; j++ )
{
if(kws.charAt(i+j) != sub.charAt(j))
{
occurence = false;
i = i+j;
break;
}
}
if (occurence)
occurences++;
// if(kws.substring(i,i+subLen).equalsIgnoreCase(sub))
// {
// //System.out .println(kws.substring(i,i+subLen));
// occurences++;
// }
}
}
System.out.println(occurences);
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
// subOccurence(40,"kakeecho");
}
}