Search code examples
c#stringalgorithmcontains

Repeated pattern. Need help understanding a submitted solution


Looking for some help to understand a solution someone else submitted. After I submitted mine, I looked at the others on leetcode to see the kind of solutions others came up with.

I came across one that was efficient and simple but I have a hard time understanding it.

string checker = (s + s).Substring(1, 2 * s.Length - 2);
return checker.Contains(s);

What I do understand : checker builds a substring between s+s starting at index 1;

String method Contain() checks for said string inside checker; However, I may be confused about the fundamental nature of Contain();

Example cases:

1.abcabcabc

ex 1. checker = "bcabcabcabcabcabc"; s checks for abcabcabc; The second should contains this since (s+s); this returns true;

2.abababc

ex 2. checker = "bababcabababc"; wouldn't it contain "abababc" bababc/abababc?; returns false;

How does Contain() actually work in C#? Preferably ELI5; please and thanks!


Solution

  • Substring length is twice input length minus 2, so the last character will also be truncated. If the input is entirely composed of a repeating "phrase", then appending itself will manifest the input value in the middle of the concatenation result. The first and last chars are truncated to avoid a match on the original input values in the concatenation

    input => append input to input => truncate first and last char => result
    
    ab => abab => ba => !contains(ab)
    abc => abcabc => bcab => !contains(abc)
    abab => abababab => bababa => contains(abab)
                         ^--^
    abcabc => abcabcabcabc => bcabcabcab => contains(abcabc)
                                ^----^