@(leetcode)[字符串, Google]
Problem
Given a long string s and short strings t1, t2, t3
(which can have different length) find the shortest substring of s which contains t1
, t2
and t3
.
Example:
s = "abcdefghijklmnopqrst", t1 = "abc", t2 = "cde", t3 = "klmn"
, return "abcdefghijklmn"
;
Solution
我们可以得到一个时间负责O(N),空间复杂度为O(1)的算法,因为题目中告知t1, t2, t3是short strings.具体的算法流程如下:
1.初始化,len为t的长度,len1-3分别为s1-3的长度,min_len=min(len1,len2,len3), max_len=max(len1, len2, len3),以及扫描的起始位置idx,s1-3找到匹配时候的索引idx1-3
2.从idx开始,查看是否找到s1的匹配,如果找到更新idx1的位置,并且判断idx1,idx2,idx3是否都大于0,如果是,则可以根据这三个位置以及他们各自的长度求出当前包含它们的最小子字符串。并更新结果。
3.同理,依次检查s2, s3是否找到匹配,如果找到就进行与步骤2一样的处理。
4.做一点小的优化,如果在某次循环中得出的子字符串长度已经等于max_len,那么就没有比较继续搜索,此时的子字符串就是结果。
Code
#include <iostream>
#include <string>
#include <utility>
#include <cstring>
#include <algorithm>
#include <cassert>
using namespace std;
typedef pair<int, int> sub_string;
int cal_end_idx(sub_string const &str) {
return str.first + str.second;
}
//计算此时包含三个字符串的最小子字符串
void cal_shortest_sub_str(int idx1, int idx2, int idx3, size_t len1,
size_t len2, size_t len3, sub_string& res) {
if(idx1 < 0 || idx2 < 0 || idx3 < 0<