文章目录
一、题目
1、题目描述
对于任何字符串,我们可以通过删除其中一些字符(也可能不删除)来构造该字符串的 子序列 。(例如,“ace” 是 “abcde” 的子序列,而 “aec” 不是)。
给定源字符串 source 和目标字符串 target,返回 源字符串 source 中能通过串联形成目标字符串 target 的 子序列 的最小数量 。如果无法通过串联源字符串中的子序列来构造目标字符串,则返回 -1。
2、基础框架
- C++版本给出的基础框架如下:
3、原题链接
https://leetcode.cn/problems/shortest-way-to-form-string/
二、解题报告
1、思路分析
(
1
)
(1)
(1)循环遍历源字符串依次匹配目标字符串,每轮循环尽可能多地匹配掉目标字符串中的字符。
(
2
)
(2)
(2)当出现该轮循环没匹配到目标字符串中的字符时,说明目标字符串中存在源字符串没有的字符,说明无法通过源字符串构建目标字符串。
2、时间复杂度
3、代码详解
class Solution {
public:
int shortestWay(string source, string target) {
int i = 0;
int lasti = -1;
int cnt = 0;
while (i < target.size() && i > lasti) {
// 如果lasti不变,说明这一轮无法去掉target字符,说明target中存在source中不存在的字符
lasti = i;
// 遍历源字符串,每次尽可能去掉更多target字符
for(int j = 0; j < source.size(); j++) {
if (i < target.size() && source[j] == target[i]) {
i++;
}
}
// 删除的次数
cnt++;
}
if (i != target.size()) {
return -1;
}
return cnt;
}
};