Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
                            ^----^
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading