[String] A001_Statistics of the number of repetitions (violence / optimization)

1. Problem

The string S is composed of n concatenated strings s, denoted as S = [s, n]. For example, ["abc", 3] = "abcabcabc".

If we can delete some characters from s2 to make it s1, then say the string s1 can be obtained from the string s2. For example, by definition, "abc" can be obtained from "abdbec", but not from "acbbe".

Now give you two non-empty strings s1 and s2 (each up to 100 characters long) and two integers 0 ≤ n1 ≤ 106 and 1 ≤ n2 ≤ 106 Now consider the strings S1 and S2, where S1 = [s1, n1] and S2 = [s2, n2].

Please find a maximum integer M that can satisfy [S2, M] from S1.

S1 satisfies [S2, M]
, that is, acbacbacbacb. After deleting any characters, the maximum number of abab will appear.
Delete all c in S1, then the remaining letters consist of 2 ababs,
so return 2
that is M = 2, S1 = [S2, 2]

输入:
s1 ="acb",n1 = 4
s2 ="ab",n2 = 2

返回:
2

Second, Solution

Method 1: Brute force matching

Enumerate s1, then count the number of occurrences of s2 in s1.

Time-out error: The time complexity of such brute force matching is O ( 100 n 1 ) O (100 * n1) , the maximum value of n1 is 10 ^ 6, and the overall calculation is 1 0 8 10^8

public int getMaxRepetitions(String s1, int n1, String s2, int n2) {
    StringBuilder sb1 = new StringBuilder(s1);
    StringBuilder sb2 = new StringBuilder(s2);
    for (int i = 1; i < n1; i++) sb1.append(s1);
    for (int i = 1; i < n2; i++) sb2.append(s2);
    
    int M = 0, k = 0;
    for (int i = 0; i < sb1.length(); i++) {
        if (sb1.charAt(i) == sb2.charAt(k)) {
            k++;
        }
        if (k == sb2.length()) {
            M++;
            k = 0;
        }
    }
    return M;
}

Complexity analysis

  • time complexity: O ( 100 × n 1 ) O (100 × n1)
  • Space complexity: O ( n ) O (n)

Method 2: Brute force optimization

Optimization one:

  • We need [s1, n1]the find [s2, n2] × M, find the maximum of M.
  • We do not need to splice s2 n2 times, instead we directly s 1 × n 1 s1 × n1 s2 are found in , and finally return T n 2 \cfrac{T}{n2} That's it.
  • Still timeout ...

Optimization 2:

  • If s1 remaining characters is not s2.length()a word, to the end.
Published 714 original articles · praised 199 · 50,000+ views

Guess you like

Origin blog.csdn.net/qq_43539599/article/details/105625096