[LeetCode] Find the Shortest Superstring II

3571. Find the Shortest Superstring II

You are given two strings, s1 and s2. Return the shortest possible string that contains both s1 and s2 as substrings. If there are multiple valid answers, return any one of them.

A substring is a contiguous sequence of characters within a string.

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
class Solution {
vector<int> PI(string& p) {
vector<int> pi(p.length());
for(int i = 1, j = 0; i < p.length(); i++) {
while(j and p[j] != p[i]) j = pi[j-1];
if(p[j] == p[i]) pi[i] = ++j;
}
return pi;
}
int kmp(string& s, string& p) {
auto pi = PI(p);
int res = 0;
for(int i = 0, j = 0; i < s.length(); i++) {
while(j and s[i] != p[j]) j = pi[j-1];
if(s[i] == p[j]) {
++j;
if(j == p.length()) return -1;
}
if(i + 1 == s.length()) return j;
}
return 0;
}
string helper(string& A, string& B) {
auto skip = kmp(A,B);
if(skip == -1) return A;
return A + B.substr(skip);
}
public:
string shortestSuperstring(string s1, string s2) {
string res1 = helper(s1,s2), res2 = helper(s2,s1);
return res1.length() > res2.length() ? res2 : res1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/07/03/PS/LeetCode/find-the-shortest-superstring-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.