1. 程式人生 > >LeetCode Repeated Substring Pattern 重複的子字串

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

給定一個非空的字串,判斷它是否可以由它的一個子串重複多次構成。給定的字串只含有小寫英文字母,並且長度不超過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;
    }