O(n) Str+Str Java solution


  • 0
    L

    Say your string s = "aba"
    Create a new string s2 = "aba" + "aba" = "abaaba"
    Now remove the first and last character of s2 = "baab"
    If s2 contains s1 then return true else false;

    Say s = "abcabc"
    s2 = "abcabcabcabc"
    new s2 = "bcabcabcab" which contains s.
    Hence return true

    public boolean repeatedSubstringPattern(String s) {
            
            if(s == null || s.length() == 0) {
                return true;
            }
            String s2 = s + s;
            s2 = s2.substring(1, s2.length());
            s2 = s2.substring(0, s2.length() - 1);
            return s2.contains(s);
        }
    

Log in to reply
 

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