I want to concatenate user input intelligently so that It removes duplicate substring in following way.
Here is what I am trying to do, not able to figure out what's missing
public class Concater {
public String concat(String s1, String s2) {
String s = s1;
int L = s2.length();
while (L > 0) {
String common = s2.substring(0, L);
if (s1.endsWith(common)) {
s = s1+common+s2.substring(L);
break;
}
L--;
}
return s;
}
public static void main(String[] args) {
Concater c = new Concater();
System.out.println(c.concat("uneasy", "easyly")+"|expected:uneasyly");
System.out.println(c.concat("concat", "catalyst")+"|expected:concatalyst");
}
}
Output
uneasyeasyly|expected:uneasyly
concatcatalyst|expected:concatalyst
Is there a better way to do it?
Your error is in the line
s = s1+common+s2.substring(L);
You are concatenating the whole of s1 plus the common part, which is already contained in s1. Try changing it to
s = s1+s2.substring(L);
and it should work (not tested, though).
s = s1+common+s2.substring(L);
The problem is that common is contained by s1 already. That's why you get two common strings.
However, you algorithm doesn't work under a more common case uneasyly + easytogo = uneasylytogo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With