Repeated Substring Paterm
题目描述:
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.)
原题地址:
https://leetcode.com/problems/repeated-substring-pattern/#/description
做法一:
public boolean repeatedSubstringPattern(String s) { boolean b = false; for(int i =1;i<=s.length()/2;i++){ //遍历所有可能性 String ele = s.substring(0,i); //子基字符串 int number = s.length()/ele.length(); if(getNewString(ele,number).equals(s)){ //判断根据子字符串得出的新字符串是否和原字符串相等 b = true; break; } } return b; } public String getNewString(String s,int m){ String str = ""; for(int i =0;i<m;i++){ str = s+str; } return str; }
做法二:
public boolean repeatedSubstringPattern(String s) { boolean b = false; int length = 1; int i = length; while(i+length<=s.length()){ String str = s.substring(0,length); //确定基字符串 if(s.substring(i,length+i).equals(str)){ //判断该字符串是否为真-基字符串 if(s.length()%length==0){ //如果基字符串能整除原字符串,则为真 b = true; } i = i+length; }else{ b = false; length++; i = length; } } return b; }