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

刷题杂感:

刷这道题的过程还是一如既往:很快想到第一种做法,然后因为时间复杂度的原因扑街了,然后又尝试了另一种更“简洁”一点的算法 /* == 我这样的菜鸡能想出来的最简洁的做法了orz*/ 刷题越多,越觉得做题的时候要多想想再码代码,得出正确的结果固然很棒,但是想出一个时间/空间复杂度较小的算法更重要。 LeetCode的题目和Lintcode相比,难度可能相差不大,但是LeetCode的测试要求更高,所有代码经常扑街orz。还有就是英文Description有时候看不懂,必须配合着example一起看才能理解题意[谁让我这个菜鸡预备程序员英语姿势水平不高呢] 共勉吧!希望能有一天可以徒手写代码,肉眼debug!

第一种做法:

    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;
    }

点赞