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







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值