repeated-substring-pattern

https://leetcode.com/problems/repeated-substring-pattern/

下面这个方法,开始我觉得挺好。可惜还是超时了。后来我就加了一个剪枝策略,只有长度能够整除总长度的子串,才需要进行比较。

package com.company;


import java.util.*;

class Solution {
    public boolean repeatedSubstringPattern(String str) {

        for (int i=1; i<=str.length()/2; i++) {
            if (str.length() % i != 0) {
                continue;
            }
            StringBuilder sb = new StringBuilder();
            sb.append(str.substring(i));
            sb.append(str.substring(0, i));
            if (str.equals(sb.toString())) {
                return true;
            }
        }
        return false;
    }
}

public class Main {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Hello!");
        Solution solution = new Solution();

        // Your Codec object will be instantiated and called as such:
        String str = "abcabcabcc";
        boolean ret = solution.repeatedSubstringPattern(str);
        System.out.printf("ret:%b\n", ret);

        System.out.println();

    }

}

 

下面是开始超时的方法,少了一个剪枝条件。

package com.company;


import java.util.*;

class Solution {
    public boolean repeatedSubstringPattern(String str) {

        for (int i=1; i<=str.length()/2; i++) {
            StringBuilder sb = new StringBuilder();
            sb.append(str.substring(i));
            sb.append(str.substring(0, i));
            if (str.equals(sb.toString())) {
                return true;
            }
        }
        return false;
    }
}

public class Main {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Hello!");
        Solution solution = new Solution();

        // Your Codec object will be instantiated and called as such:
        String str = "abcabcabcc";
        boolean ret = solution.repeatedSubstringPattern(str);
        System.out.printf("ret:%b\n", ret);

        System.out.println();

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值