[LeetCode 459] Repeated Substring Pattern

本文探讨了一种检测字符串是否由重复子串构成的方法。通过分析不同示例,如abab和abcabcabcabc,阐述了如何利用字符串拼接技巧高效解决此问题。并提供了一段C++代码实现,其运行效率高于76.88%的在线提交。

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

 分析

这道题暴力搜索所有重复的可能,s的长度为length,搜索<length,所有可以整除length的数值,然后判断是否是重复的。

看到还有一种更巧妙的解法,如果s为重复的,例如可以分为n个重复的子串,n>=2,那么s1 = s+s肯定也会有2*n的重复的子串,那么将s1的首尾字母去除后,s1仍然包含2*n-2个重复的子串,那么s可以在s1中找到。但是这个解法需要证明不重复的子串s这样操作一定不存在s1中。这个证明的解法还没有想明白。

Code

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        int length = s.size();
        if (length == 0)
            return true;
        
        string s1 = s + s;
        s1.pop_back();
        s1.erase(0, 1);
        if (s1.find(s) == std::string::npos)
            return false;
        else
            return true;
    }
};

运行效率

Runtime: 36 ms, faster than 76.88% of C++ online submissions for Repeated Substring Pattern.

Memory Usage: 14.2 MB, less than 88.06% of C++ online submissions forRepeated Substring Pattern.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值