I have two strings s1 and s2.
I have to check what is the largest occurence of letters in s2 that are in s1.
For example:
s1="xyz"
s2="abxyryxzycx"
it would then return 4 since "yxzy" is the largest substring with all the letters in s1.
It has to be recursive.
My problem is how to keep a runningtab of which substring is largest.
my code is
private static int checkCounter(int oldCounter, int counter)
{
if (oldCounter<counter)
return counter;
else
return oldCounter;
}
/**
* this method checks two strings if they have same letters and calls with overloading a method with same name.
* checks if we reached the last letter and returns the counter
* if not calls the other method from it with the two strings
* @param s1 a string
* @param s2 a string
*/
public static int maxSection (String s1, String s2)
{
int counter=0;
int oldCounter;
if (s2.charAt(0)== s2.charAt(s2.length()-1))
{
oldCounter=counter;
return checkCounter(oldCounter,counter);
}
else
{
oldCounter=counter;
return maxSection(s1,s2,counter,oldCounter);
}
}
/** method called from maxSection that is originally called with two strings
* it checks if we have reached the end of the string and if yes returns the counter
* if not it checks if the first letter of each string is the same.
* if not it moves forward one space on string 1 and checks again if it is equal
* @param s1 a string
* @param s2 a string
* @param counter the counter
* @param oldCounter the old counter for comparison
*/
public static int maxSection(String s1, String s2, int counter, int oldCounter)
{
if (s2.charAt(0)==s2.charAt(s2.length()-1))
{
if (oldCounter<counter)
oldCounter=counter;
s1=s1.substring(1);
return oldCounter;
}
else if (s2.charAt(0)==s1.charAt(0))
{
counter++;
return maxSection(s2.substring(1),s1.substring(0),counter, oldCounter);
}
else
return maxSection(s2.substring(0),s1.substring(1),counter, oldCounter);
}
public static void main()
{
String s1="xyz";
String s2 = "abxyryxzycx";
maxSection(s1,s2);
}
Any help would be appreciated.
Leeba