【LeetCode - 1055】形成字符串的最短路径

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;
    }
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值