LeetCode Repeated Substring Pattern 重复的子字符串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sun_wangdong/article/details/82988096

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

给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。

示例 1:

输入: "abab"

输出: True

解释: 可由子字符串 "ab" 重复两次构成。

示例 2:

输入: "aba"

输出: False

示例 3:

输入: "abcabcabcabc"

输出: True

解释: 可由子字符串 "abc" 重复四次构成。 (或者子字符串 "abcabc" 重复两次构成。)

题解:这道题刚拿到后,并没有思路,能想到的也是通过两层循环,依次将原始字符串搜寻子字符串,然后再对比该子字符串是否可以重复构成原始字符串。但是后来网上看到一个思路,可以稍微化简一些,那就是因为要找到一个子字符串,能够重复构成该原始字符串,那么必然该子字符串的长度能被该字符串整除,基于这个常识,只需要从原始字符串的一半开始搜寻即可。如果找到的子字符串的长度能被原始字符串整除,那么再用该子字符串构造成一个完整的字符串,长度与原始字符串相同,然后再对比,两者如果相同,那么就可以结束循环;如果一致搜寻到只有一个字符为止,都不能满足题意,那么直接返回false。

    public static boolean repeatedSubstringPattern(String s)
    {
        int l = s.length();	
        for(int i = l/2; i >= 1; i--) 
        {		
            if(l % i == 0) 
            {			
                int m = l/i;			
                String subS = s.substring(0,i);			
                StringBuilder sb = new StringBuilder();			
                for(int j = 0; j < m; j++) 			
                    sb.append(subS);				
                if(sb.toString().equals(s)) 
                    return true;		
            }	
        }	
        return false;
    }

猜你喜欢

转载自blog.csdn.net/sun_wangdong/article/details/82988096