You are given a 0-indexed array words containing n strings.
Let’s define a join operation join(x, y) between two strings x and y
as concatenating them into xy. However, if the last character of x is equal to the first character of y, one of them is deleted.
For example join("ab", "ba") = "aba" and join("ab", "cde") = "abcde".
You are to perform n - 1join operations. Let str0 = words[0].
Starting from i = 1 up to i = n - 1, for the ith operation, you can do one of the following:
Make stri = join(stri - 1, words[i])
Make stri = join(words[i], stri - 1)
Your task is to minimize the length of strn - 1.
Return an integer denoting the minimum possible length ofstrn - 1.
Input: words =["aa","ab","bc"]Output: 4Explanation: In this example, we can perform join operations in the following order to minimize the length of str2:str0 ="aa"str1 = join(str0,"ab")="aab"str2 = join(str1,"bc")="aabc"It can be shown that the minimum possible length of str2 is4.
Input: words =["ab","b"]Output: 2Explanation: In this example, str0 ="ab", there are two ways to get str1:join(str0,"b")="ab" or join("b", str0)="bab".The first string,"ab", has the minimum length. Hence, the answer is2.
Input: words =["aaa","c","aba"]Output: 6Explanation: In this example, we can perform join operations in the following order to minimize the length of str2:str0 ="aaa"str1 = join(str0,"c")="aaac"str2 = join("aba", str1)="abaaac"It can be shown that the minimum possible length of str2 is6.
At each step, we can join the next word to the left or right of the current string. The optimal solution can be found by dynamic programming, where the state keeps track of which word was used last and from which side. We minimize the length by considering both options at each step.
Define dp[i][0] as the minimum length after processing the first i words, ending with the i-1th word on the left; dp[i][1] for ending with the i-1th word on the right.
Initialize dp[0][0] = dp[0][1] = len(words[0]).
For each i from 1 to n-1:
For both previous states (left/right), try joining the new word to the left or right, and update the minimum length accordingly, considering the join rule (delete one char if last of left == first of right).
The answer is the minimum of the two states after all words are processed.