Repeated Substring Pattern

本文介绍了一种基础算法,用于检查给定的非空字符串是否可以通过重复追加其自身的子字符串来构建。通过具体实例展示了如何实现这一算法,并提供了完整的代码示例。

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 开始,从下表0开始取字串(字串的长度从1 ~ str.length-2)然后依次跟后面比较,如果都相同,那么说明是可以拼成的,否则不能。


代码:


public boolean repeatedSubstringPattern(String str) {
        if(str == null || str.length() == 0) return true;
        int len = str.length();
        for(int i=1;i<len;i++){
            if(len % i == 0){
                String sub = str.substring(0, i);
                boolean isSub = true;
                for(int j=i;j<len;j++){
                    if(sub.charAt(j%sub.length()) != str.charAt(j)){
                        isSub = false;
                        break;
                    }
                }
                if(isSub){
                    return true;
                }
            }
        }
        return false;
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值