标签:let abc string ati 遍历 ++ tostring public nbsp
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.)
分析:
1.重复字符串的长度肯定会被输入字符串长度整除
2.遍历可能的重复字符串长度i,从s.length/2开始,不可能大于字符串的一半
3.如果有个i被输入字符串整除,那么将该(0,i)的字符串合并
4.与原字符串相比较,如果相等,则为重复字符串。
实现代码如下:
class Solution { public boolean repeatedSubstringPattern(String s) { int len = s.length(); for(int i = len/2; i>=1;i--){ if(len%i == 0){ int m = len/i; //代码有m个长度为i的重复字符串 String str = s.substring(0, i); //取出(0,i)的字符串 StringBuffer sb = new StringBuffer(); for(int j = 0;j < m;j++){ sb.append(str); } if(sb.toString().equals(s)){ return true; } } } return false; } }
Repeated Substring Pattern --重复字符串
标签:let abc string ati 遍历 ++ tostring public nbsp
原文地址:http://www.cnblogs.com/linwx/p/7745971.html