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

重复的子字符串。

题意很好理解,给一个字符串,请问这个字符串是否是一个子串拼接成的。这个题的思想不涉及算法。既然是判断这个字符串是否是由一个较小的子串拼接而成的,如果input字符串的长度小于2,则一定是错的。接着如何找子串呢?首先,这个子串的长度应该是介于1 - s.length() / 2之间,然后需要用substring一点点去截取一个temp string,判断这个temp string是否能整除字符串的总长,如果不是,则这个temp string就不是一个符合题意的子串。如果是,则试着用这个temp string拼接M次,看看最后拼接的结果是否和input字符相同。

时间O(n^2)

空间O(n)

Java实现

 1 class Solution {
 2     public boolean repeatedSubstringPattern(String s) {
 3         // corner case
 4         if (s.length() < 2) {
 5             return false;
 6         }
 7 
 8         // normal case
 9         int len = s.length();
10         for (int i = len / 2; i >= 1; i--) {
11             if (len % i == 0) {
12                 // 有m个长度为i的substring
13                 int m = len / i;
14                 String sub = s.substring(0, i);
15                 StringBuilder sb = new StringBuilder();
16                 // 用m个substring i拼成一个长的string 再和s比较
17                 for (int j = 0; j < m; j++) {
18                     sb.append(sub);
19                 }
20                 if (sb.toString().equals(s)) {
21                     return true;
22                 }
23             }
24         }
25         return false;
26     }
27 }

JavaScript实现

 1 /**
 2  * @param {string} s
 3  * @return {boolean}
 4  */
 5 var repeatedSubstringPattern = function (s) {
 6     // corner case
 7     if (s.length < 2) {
 8         return false;
 9     }
10 
11     // normal case
12     let len = s.length;
13     for (let i = Math.floor(len / 2); i >= 1; i--) {
14         if (len % i == 0) {
15             let temp = '';
16             let m = Math.floor(len / i);
17             for (let j = 0; j < m; j++) {
18                 temp += s.substring(0, i);
19             }
20             if (temp === s) {
21                 return true;
22             }
23         }
24     }
25     return false;
26 };

相关题目

459. Repeated Substring Pattern

686. Repeated String Match

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13551774.html