Leetcode-459. Repeated Substring Pattern

前言:正好碰见Leetcode有一次在线笔试,测试一下,Rank:92/807。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客
——————————————————————————————

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input: "abab"

Output: True

Explanation: It's the substring "ab" twice.

Example 2:

Input: "aba"

Output: False

Example 3:

Input: "abcabcabcabc"

Output: True

Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
这个题目解的不是很好,大致就是部长从1增长到n/2,然后第一次满足重复结构则退出。时间复杂度O(n^2)。在循环过程中进行了一定程度的优化。 Your runtime beats 45.76% of java submissions.

public class Solution {
    public boolean repeatedSubstringPattern(String str) {
        if(str.length() < 2) return false;
        int i = 1;
        boolean flag = false;
        while(i<=str.length()/2){
            if(str.length() % i ==0){
                flag = check(str,i);
            }
            i++;
            if(flag) break;
        }
        return flag;
    }


    public boolean check(String str,int distance){
        for(int i = distance; i < str.length(); i+= distance){
            for(int j = 0; j < distance;j ++)
                if(str.charAt(i + j) != str.charAt(j)) return false;;
        }
        return true;
    }
}





你可能感兴趣的:(算法)