less than 1 minute read

3029. Minimum Time to Revert Word to Initial State I

You are given a 0-indexed string word and an integer k.

At every second, you must perform the following operations:

  • Remove the first k characters of word.
  • Add any k characters to the end of word.

Note that you do not necessarily need to add the same characters that you removed. However, you must perform both operations at every second.

Return the minimum time greater than zero required for word to revert to its initial state.

Solution

class Solution {
    public int minimumTimeToInitialState(String word, int k) {
        String copy = new String(word);
        int count = 0;

        do {
            word = word.substring(k) + "*".repeat(k);
            count++;
        } while (!isStringEqual(copy, word));

        return count;

    }

    private boolean isStringEqual(String str1, String str2) {
        if (str1.length() != str2.length()) {
            return false;
        }

        for (int i = 0; i < str1.length(); i++) {
            if (str2.charAt(i) == '*') {
                continue;
            } else if (str1.charAt(i) != str2.charAt(i)) {
                return false;
            }
        }

        return true;
    }
}

Retro

  1. the adoption of “*” to represent omni character is very inspiring
  2. the API of string manipulation
    1. the usage of substring, passing K represent K to end
    2. replicate a character : “*“.repeat(K)