Header Ad

Leetcode Repeated Substring Pattern problem solution

In this Leetcode Repeated Substring Pattern problem solution, we have given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.

Leetcode Repeated Substring Pattern problem solution


Problem solution in Python.

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        for i in range(2, len(s) // 2 + 1):
            if len(s) % i != 0:
                continue
                
            ss = s[:i]
            for j in range(i, len(s), i):
                if s[j:j+i] != ss:
                    break
            else:
                return True
                    
        return False



Problem solution in Java.

static boolean repeatedSubstringPattern(String s) {

        int end_partition = 1;
        if(s == null || s.length() <= 1) return false;

        while(end_partition <= s.length() - 1) {

            String substring = s.substring(0, end_partition);
            int substring_length = substring.length();

            if(s.length() % substring_length == 0) {

                int susbtring_in_string = s.length() / substring_length;
                StringBuilder sb = new StringBuilder();
                for(int i = 0; i < susbtring_in_string; i++) {
                    sb.append(substring);
                }

                if(s.equals(sb.toString())) {
                    return  true;
                }
            }
            end_partition++;
        }

        return false;
    }


Problem solution in C++.

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
    string str=s+s;
        str.pop_back();
        str=str.substr(1);
        if(str.find(s)!=string::npos)
            return true;
        return false;
    }
};


Problem solution in C.

bool judge_even(char* str, int len) {
    int i = len / 2;
    int j = 0;
    while(j < i) {
        if(str[j] != str[i+j])
            return false;
        ++j;
    }
    return true;
}

bool judge_odd(char* str, int len) {
    int i = len / 3;
    int j = 2 * i;
    int k = 0;
    while(k < i) {
        if(str[k] != str[i+k] || str[k] != str[j+k])
            return false;
        ++k;
    }
    return true;
}

bool judge_prime(char* str, int len) {
    char pre = str[0];
    int i;
    for(i = 1; i < len; ++i) {
        if(str[i] != pre)
            return false;
        pre = str[i];
    }
    return true;
}

bool repeatedSubstringPattern(char* str) {
    int len = strlen(str);
    
    if(1 == len) return false;
    
    if(len % 3 == 0 && len % 2 == 0) {
        if(judge_db3(str, len)) return true;
        return judge_even(str, len);
    }
    
    if(len % 3 == 0) {
        return judge_db3(str, len);
    }
    
    if(len % 2 == 0) {
        return judge_even(str, len);
    }
    
    return judge_prime(str, len);
}


Post a Comment

0 Comments