1、题目描述
2、解题思路
题目要求的是子序列,且通过示例可知,子序列可以重复使用。
使用贪心算法,假设 source = “xyz”, target = “xzyxz”。
定义一个指针 idx 指向 target,初始为 0;
遍历 source,是否找得到 target 中 idx 起始的子序列。
1、例如当 idx = 0 时,存在子序列 “xz” 匹配 target 的前两个字符,子序列找到一个;
2、idx 更新为 2,即从 source 中找到匹配 target 的索引 2 开始的字符,找到了一个 “y”,idx 更新为 3,子序列又找到一个;
3、从 source 中找到 “xz” 来匹配 target 从 3 开始的字符,子序列又找到一个。
4、如果遍历一遍 source 都没有找到一个字符来匹配 idx 起始的 target 字符,说明 target 存在 source 没有的字符,返回 -1。
5、当 idx == target.length 时,说明匹配完毕。
3、解题代码
class Solution {
public int shortestWay(String source, String target) {
int minCount = 0;
char[] targets = target.toCharArray();
int idx = 0;
while (idx < targets.length) {
int next = greedyFind(source, targets, idx);
if (next == -1) {
return -1;
} else {
minCount++;
idx = next;
}
}
return minCount;
}
private int greedyFind(String source, char[] target, int targetIdx) {
char[] sources = source.toCharArray();
int cache = targetIdx; // 缓存 targetIdx
int sourceIdx = 0;
while (sourceIdx < sources.length && targetIdx < target.length) {
if (sources[sourceIdx] == target[targetIdx]) {
targetIdx++;
}
sourceIdx++;
}
if (targetIdx == cache) {
// 一个字符都没匹配上
return -1;
}
return targetIdx;
}
}