Skip to content

1055. Shortest Way to Form String 👍

Approach 1: Greedy

  • Time: $O(|\texttt{source}||\texttt{target}|)$
  • Space: $O(1)$, $O(26 \cdot |\texttt{source}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int shortestWay(string source, string target) {
    int ans = 0;

    for (int i = 0; i < target.length();) {
      const int prevIndex = i;
      for (int j = 0; j < source.length(); ++j)
        if (i < target.length() && source[j] == target[i])
          ++i;
      // all chars in source didn't match target[i]
      if (i == prevIndex)
        return -1;
      ++ans;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int shortestWay(String source, String target) {
    int ans = 0;

    for (int i = 0; i < target.length();) {
      final int prevIndex = i;
      for (int j = 0; j < source.length(); ++j)
        if (i < target.length() && source.charAt(j) == target.charAt(i))
          ++i;
      // all chars in source didn't match target[i]
      if (i == prevIndex)
        return -1;
      ++ans;
    }

    return ans;
  }
}