LeetCode(459):重复的子字符串 Repeated Substring Pattern(Java)

234 篇文章 1 订阅
177 篇文章 0 订阅
该篇博客介绍了如何解决LeetCode中的一个字符串问题,检查给定字符串是否能由其重复子串组成。博主分享了两种解决方案,包括遍历子串并检查是否为重复模式,以及通过构建双倍字符串来查找子串。示例展示了如何判断字符串如'abab'、'aba'和'abcabcabcabc'的情况。
摘要由CSDN通过智能技术生成

2021.1.22 LeetCode 从零单刷个人笔记整理(持续更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

如果s中包含重复的子字符串,那么说明s中至少包含两个子字符串,s+s至少包含4个字串,前后各去掉一位,查找s是否在新构建的字符串中。


传送门:重复的子字符串

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。

示例 1:
输入: "abab"
输出: True
解释: 可由子字符串 "ab" 重复两次构成。

示例 2:
输入: "aba"
输出: False

示例 3:
输入: "abcabcabcabc"
输出: True
解释: 可由子字符串 "abc" 重复四次构成。 (或者子字符串 "abcabc" 重复两次构成。)


package Problems;

/**
 * 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。
 */
public class RepeatedSubstringPattern {
    public boolean repeatedSubstringPattern(String s) {
        int len = s.length();
        for (int i = 1; i <= len >> 1; i++) {
            if (len % i == 0) {
                String pattern = s.substring(0, i);
                boolean match = true;
                for (int j = i; j < len; j += i) {
                    if (!s.substring(j, j + i).equals(pattern)) {
                        match = false;
                        break;
                    }
                }
                if (match) {
                    return true;
                }
            }
        }
        return false;
    }

    //如果s中包含重复的子字符串,那么说明s中至少包含两个子字符串,s+s至少包含4个字串,前后各去掉一位,查找s是否在新构建的字符串中。
    public boolean repeatedSubstringPattern2(String s) {
        String dblStr = s + s;
        return dblStr.substring(1, dblStr.length() - 1).contains(s);
    }
}




#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值