题目原址
https://leetcode.com/problems/repeated-substring-pattern/description/
题目描述
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.
Example1:
Input: “abab”
Output: True
Explanation: It’s the substring “ab” twice.
Example2:
Input: “aba”
Output: False
Example3:
Input: “abcabcabcabc”
Output: True
Explanation: It’s the substring “abc” four times. (And the substring “abcabc” twice.)
解题思路
题目要求是要判断给定的字符串的字符是否全部都是有规律重复的字符,如果是则返回true
- (1)定义一个新的字符串s1,该字符串的值等于给定的字符串的与给定字符串连接在一起
- (2)如果s1字符串的第二个字符到倒数第二个字符中间的所有字符包含给定判断的字符串,说明符合条件。理由:去掉s1字符串的第一个字符,并且去掉s1字符串的最后一个字符,如果给定的字符是重复的话,那么(定的字符串的与给定字符串连接在一起)<-操作 就填补了原字符串的去掉部分。
AC代码
class Solution {
public boolean repeatedSubstringPattern(String s) {
String s1 = s + s;
return s1.substring(1, s1.length() - 1).contains(s);
}
}
感谢
https://leetcode.com/problems/repeated-substring-pattern/discuss/94344/Simple-Java-solution-2-lines