Shortest String That Contains Three Strings

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution:
    def solve(self, first, second):
        if second in first:
            return first
        if first in second:
            return second

        firstLen, secondLen = len(first), len(second)
        merged1 = first + second
        for i in range(min(firstLen, secondLen) - 1, -1, -1):
            if first[firstLen - i - 1:] == second[:i + 1]:
                merged1 = first + second[i + 1:]
                break

        first, second = second, first
        firstLen, secondLen = len(first), len(second)
        merged2 = first + second
        for i in range(min(firstLen, secondLen) - 1, -1, -1):
            if first[firstLen - i - 1:] == second[:i + 1]:
                merged2 = first + second[i + 1:]
                break

        return min(merged1, merged2, key=lambda x: (len(x), x))

    def minimumString(self, a, b, c):
        ab = self.solve(a, b)
        bc = self.solve(b, c)
        ac = self.solve(a, c)
        ans1 = self.solve(ab, c)
        ans2 = self.solve(bc, a)
        ans3 = self.solve(ac, b)

        temp = [ans1, ans2, ans3]
        temp.sort(key=lambda x: (len(x), x))

        return temp[0]