Shortest Way to Form String

Problem

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., “ace” is a subsequence of “abcde” while “aec” is not).

Given two strings source and target, return the minimum number of subsequences of source such that their concatenation equals target. If the task is impossible, return -1.

Example 1:

Input: source = "abc", target = "abcbc"
Output: 2
Explanation: The target "abcbc" can be formed by "abc" and "bc", which are subsequences of source "abc".

Example 2:

Input: source = "abc", target = "acdbc"
Output: -1
Explanation: The target string cannot be constructed from the subsequences of source string due to the character "d" in target string.

Example 3:

Input: source = "xyz", target = "xzyxz"
Output: 3
Explanation: The target string can be constructed as follows "xz" + "y" + "xz".

Constraints:

  • 1 <= source.length, target.length <= 1000
  • source and target consist of lowercase English letters.

Solution

class Solution {
    public int shortestWay(String source, String target) {
        var sourceIdx = 0;
        var targetIdx = 0;
        var times = 1;
        var ok = false;

        while (targetIdx < target.length()) {
            // loop around
            if (sourceIdx == source.length()) {
                if (!ok) {
                    return -1;
                }
                sourceIdx = 0;
                times += 1;
                ok = false;
            }

            // read in character-by-character from source
            if (source.charAt(sourceIdx) == target.charAt(targetIdx)) {
                targetIdx += 1;
                ok = true;
            }
            // always increment
            // we either consume the character or can't use it
            sourceIdx += 1;
        }

        return times;
    }
}

Recent posts from blogs that I like

Sequoia introduces pinning to iCloud Drive

If you have Optimise Mac Storage enabled for iCloud Drive, this new feature lets you pin the files you want to be stored locally and not evicted. Full details.

via The Eclectic Light Company

Notes on running Go in the browser with WebAssembly

Recently I've had to compile Go to WebAssembly to run in the browser in a couple of small projects (#1, #2), and in general spent some time looking at WebAssembly. I find WebAssembly to be an exciting technology, both for the web and for other uses (e.g. with WASI); specifically, it's pretty great t...

via Eli Bendersky

I fixed the strawberry problem because OpenAI couldn't

Remember kids: real winners cheat

via Xe Iaso