459. Repeated Substring Pattern

来源:互联网 发布:淘宝moschino 编辑:程序博客网 时间:2024/05/16 18:38

原题
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.)
题目大意
给你一个非空的字符串,判断字符串是不是由它的子字符串复制构成的
思路
从字符串长度的一半开始倒序,用变量i来记录,如果字符串的长度能够整除i,则继续判断;否则i逐渐递减。如果能够整除,用j来记录倍数,看i的j倍与i的j+1倍之间的字符串是不是与(0,i)相同,不相同,则i减小;如果从1到长度除以i的倍都相同,则说明字符串是由子字符串构成的
代码

public class Solution {    public boolean repeatedSubstringPattern(String str) {        if(str.length()==0||str==null) return true;         //使用倒序的方式        for(int i=str.length()/2;i>=1;i--){            if(str.length()%i==0){            int m=str.length()/i;            //选出子字符串            String repeat=str.substring(0, i);            int j=0;            //使用循环的方式,不断选出i的j倍,然后查看子字符串是否与原来的相同            for(;j<m;j++){                if(!repeat.equals(str.substring(i*j, i+j*i)))                    break;            }            if(j==m) return true;            }        }        return false;    }}

原题地址

0 0
原创粉丝点击