129.Repeated Substring Pattern(重复子串模式)

博客围绕判断非空小写英文字符串能否由子串重复构成展开。给出题目描述及示例,解答方法是从字符串一半遍历到1,若能被原字符串长度整除,取首子串重复拼接,若与原字符串相等则可拆分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

给定非空字符串检查是否可以通过获取它的子字符串并将子字符串的多个副本附加在一起来构造它。 您可以假设给定的字符串仅由小写英文字母组成,其长度不超过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.)

解答:

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        int l=s.length();
        for(int i=l/2;i>=1;i--){
            if(l%i==0){
                int m=l/i;
                String subS=s.substring(0,i);
                StringBuilder sb=new StringBuilder();
                for(int j=0;j<m;j++){
                    sb.append(subS);
                }
                if(sb.toString().equals(s))
                    return true;
            }
        }
        return false;
    }
}

详解:

从字符串的一半遍历到1,如果可以被原字符串长度整除,说明可以分成m个子串,取从0开始的第一个子串重复m遍,拼接起来若与原字符串相等,即表示原字符串可以被拆分成m个子串。

转载于:https://www.cnblogs.com/chanaichao/p/9565651.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值