Skip to content

Latest commit

 

History

History
77 lines (57 loc) · 1.87 KB

_1055. Shortest Way to Form String.md

File metadata and controls

77 lines (57 loc) · 1.87 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : March 30, 2025

Last updated : March 30, 2025


Related Topics : Two Pointers, String, Binary Search, Greedy

Acceptance Rate : 61.25 %


Solutions

Python

class Solution:
    def shortestWay(self, source: str, target: str) -> int:
        s = t = output = 0

        while t < len(target) :
            loop = len(source)

            while loop >= 0 and source[s] != target[t] :
                s += 1
                loop -= 1
                if s >= len(source) :
                    output += 1
                    s -= len(source)

            if source[s] != target[t] :
                return -1

            s += 1
            t += 1
            if s >= len(source) :
                output += 1
                s -= len(source)

        if s > 0 :
            output += 1

        return output
class Solution:
    def shortestWay(self, source: str, target: str) -> int:
        s = output = 0

        for t in target :
            for _ in repeat(None, len(source)) :
                if source[s] == t :
                    break
                s = (s + 1) % len(source)
                output += 1

            if source[s] != t :
                return -1
            output += 1
            s = (s + 1) % len(source)

        return ceil(output / len(source))