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

判断一个非空的字符串是否是一个子字符串拼接多次构成的。

思路和代码

直观的思路就是选取所有可能的子字符串,并且将剩余的字符串按照等长截断,将每一段和预期的子字符串进行比较,判断是否相等。代码如下,可以参考注释理解:

    public boolean repeatedSubstringPattern(String s) {
        int length = s.length();
        //i为子字符串长度
        for(int i = length / 2 ; i>=1 ; i--) {
            if(length % i == 0) {
                //重复的次数
                int repeatCount = length / i;
                //假设的重复的子字符串
                String subString = s.substring(0, i);
                int j = 1;
                for( ; j

你可能感兴趣的:(string,java,leetcode)