Simple Java solution, 2 lines


  • 17
    F
        public boolean repeatedSubstringPattern(String str) {
            String s = str + str;
            return s.substring(1, s.length() - 1).contains(str);
        }
    

  • 0
    I

    @fhqplzj Neat solution, Can you please explain the logic behind your solution?


  • 0

    awesome solution! I want to know how you came up with this one ,too


  • 2
    F

    I get the idea from python solution, refer to for explanation.


  • 0
    G

    @ironman7 "Neat solution, Can you please explain the logic behind your solution?"
    Hhahaha... How do u get then it is a neat one??


  • 0

    This is an amazing solution. Let me try if I can explain it.
    The program first copies the original str and makes it twice longer. Let's say the given str = "abab". We will have s = "abab abab" (I put a blank space in the middle to make it clear). Then we get the substring of s by dropping the first and last character, which is "a(bab aba)b" (string inside parenthesis is the substring we get). If the original str is repeated, we can construct it from the substring we just get. This is because we can get some part of str from the first pattern ("bab") and get the other part from the second pattern ("aba"). This works only if str consisted of its repeated substring, otherwise we cannot get str from the s.
    I hope this helps.


  • 1

    @dilyar Thank you for translating the program. I guess most people understand what he or she write. But can you explain more about "This is because we can get some part of str from the first pattern ("bab") and get the other part from the second pattern ("aba"). " because this is the only line you explain and this still makes me confused.
    Thanks


  • 0
    J

    Amazing solution.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.