oj459. Repeated Substring Pattern

本文介绍了一种通过检查字符串是否能由一个子串重复构成的方法,并提供了两种解决方案:一种是通过替换子串来验证,另一种是通过构建新的字符串进行比较。后者在性能上更优。

摘要生成于 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.

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.)

翻译:

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

示例1:

输入: “abab” 输出: True 说明:这是子串“ab”两次。




示例2:

输入: “aba” 输出: False


示例3:

输入: “abcabcabcabc” 输出: True 说明:这是子串“abc”四次。(和子串“abcabc”两次)

超时思路:从字符串开始截取i个字符,替换这些字符为空,若整个字符串变为空,则可以由子串组成。但超时了。

public boolean repeatedSubstringPattern(String s) {
        int len = s.length();
        for(int i=1; i<=len/2 ; i++){
            String temp = s;
            String subs = temp.substring(0,i);
            String rp_temp = temp.replaceAll(subs,"");//替换时subs已经为字符串,要熟悉正则表达式的使用
            if(rp_temp.isEmpty()) return true;
        }
        return false;
    }
答案思路:也是先截取部分字符,不同点在于用截取的字符串组成新字符串与原字符对比,这里StringBuilder性能更快。

public boolean repeatedSubstringPattern(String s) {
        int len = s.length();
        for(int i=1; i<=len/2 ; i++){
            if(len%i == 0){//整串字符数为子串的整数倍
            int m = len/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;
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值