Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inteligently concat two strings so as to ignore duplicate substring

I want to concatenate user input intelligently so that It removes duplicate substring in following way.

  • uneasy + easyly = uneasyly
  • concat + catalyst = concatalyst

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?

like image 329
hiran Avatar asked Dec 10 '22 04:12

hiran


2 Answers

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).

like image 149
misberner Avatar answered Dec 11 '22 17:12

misberner


 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

like image 31
ComfortablyNumb Avatar answered Dec 11 '22 18:12

ComfortablyNumb