Repeated Substring Pattern

题目地址:https://leetcode.com/problems/repeated-substring-pattern/

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.)

这个问题是要看整个字符串是不是由某个字符串组成的(字符串本身不算)。

如果一个字符串是由某个子字符串组成的,那么这个字符串的长度肯定是这个子字符串长度的倍数,也就是说子字符串长度是这个字符串长度的约数。

那好,有了以上的判断,那就是说如果一个字符串存在所谓的重复字符串模式(Repeated Substring Pattern,简称RSP)的话,那么RSP的可能长度的数目与这个字符串约数的数目是相同的。

而且还有一个特点:RSP肯定是这个字符串的前缀。

有了这些推断,代码就好写多了。
代码实现:

public class RepeatedSubstringPattern {
    public boolean repeatedSubstringPattern(String str) {
        int len = str.length();
        List<Integer> dividerList = new ArrayList<Integer>();

        for (int i = 1; i < len; i++) {
            if (len % i == 0)
                dividerList.add(i);
        }

        for (int i : dividerList) {
            String subStr = str.substring(0, i);
            boolean allEqual = true;
            for (int k = 0; k < len / i; k++) {
                // If there is any unequal, then this substring is not the repeat pattern, try next substring.
                // If there are all equal, then this substring is the repeat pattern.
                if (!subStr.equals(str.substring(k * i, (k + 1) * i))) {
                    allEqual = false;
                    break;
                } else {
                    continue;
                }
            }
            if (allEqual) {
                System.out.println(subStr);
                return true;
            }
            else
                continue;
        }
        return false;
    }

    public static void main(String[] args) {
        RepeatedSubstringPattern repeatedSubstringPattern = new RepeatedSubstringPattern();
        System.out.println(repeatedSubstringPattern.repeatedSubstringPattern("abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij"));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值