2800. Shortest String That Contains Three Strings

Difficulty:
Related Topics:
Similar Questions:

Problem

Given three strings a, b, and c, your task is to find a string that has the** minimum** length and contains all three strings as substrings. If there are multiple such strings, return the** ****lexicographically** **smallest **one.

Return a string denoting the answer to the problem.

Notes

Example 1:

Input: a = "abc", b = "bca", c = "aaa"
Output: "aaabca"
Explanation:  We show that "aaabca" contains all the given strings: a = ans[2...4], b = ans[3..5], c = ans[0..2]. It can be shown that the length of the resulting string would be at least 6 and "aaabca" is the lexicographically smallest one.

Example 2:

Input: a = "ab", b = "ba", c = "aba"
Output: "aba"
Explanation: We show that the string "aba" contains all the given strings: a = ans[0..1], b = ans[1..2], c = ans[0..2]. Since the length of c is 3, the length of the resulting string would be at least 3. It can be shown that "aba" is the lexicographically smallest one.

Constraints:

Solution (Java)

class Solution {
    private String merge(String s1, String s2) {
        if (s1.contains(s2)) return s1;
        for (int i = 0; i < s1.length(); i++) {
            if (s2.startsWith(s1.substring(i))) return s1.substring(0, i) + s2;
        }
        return s1 + s2;
    }

    public String minimumString(String a, String b, String c) {
        String res = "";
        int l = Integer.MAX_VALUE;
        for (String s : new String[]{
            merge(merge(a, b), c),
            merge(merge(b, a), c),
            merge(merge(c, b), a),
            merge(merge(b, c), a),
            merge(merge(a, c), b),
            merge(merge(c, a), b)
        }) {
            if (s.length() < l) {
                res = s;
                l = s.length();
            } else if (s.length() == l) {
                res = res.compareTo(s) < 0 ? res : s;
            }
        }
        return res;
    }
}

Explain:

nope.

Complexity: