打卡 DAY 29 重复的子字符串

文章介绍了一种通过计算字符串前缀表来找出最长相等前后缀的方法,用于判断字符串是否由重复子串组成。在解题过程中,首先计算next数组,然后根据next数组确定最小重复子串的长度,最后检查字符串是否能被该长度整除。时间复杂度和空间复杂度均为O(n)。
摘要由CSDN通过智能技术生成

力扣原题链接

一、题目描述

二、思路

先计算出字符串前缀表,当满足题意时,最长相等前后缀的值为 next [ sLen - 1 ] ,并且满足 sLen - next [ sLen - 1 ] 的值为最小重复子串的长度 minLen,此时 sLen % minLen == 0。如图:

 

三、解题过程

  • 实现计算字符串前缀表接口函数

void getNext(char* s, int* next, int sLen){
    int j = 0, i = 1;
    next[j] = 0;
    for(; i < sLen; i++){
        while(j - 1 >= 0 && s[j] != s[i]){
            j = next[j - 1];
        }
        if(s[j] == s[i]) j++;
        next[i] = j;
    }
  • 得到最长相等前后缀长度后判断

bool repeatedSubstringPattern(char * s){
    int sLen = strlen(s);
    int* next = (int*)malloc(sizeof(int) * sLen);
    getNext(s, next, sLen);
    int minLen = sLen - next[sLen - 1];
    if(next[sLen - 1] != 0 && sLen % minLen == 0) return true;
    return false;
}

四、代码

void getNext(char* s, int* next, int sLen){
    int j = 0, i = 1;
    next[j] = 0;
    for(; i < sLen; i++){
        while(j - 1 >= 0 && s[j] != s[i]){
            j = next[j - 1];
        }
        if(s[j] == s[i]) j++;
        next[i] = j;
    }
}

bool repeatedSubstringPattern(char * s){
    int sLen = strlen(s);
    int* next = (int*)malloc(sizeof(int) * sLen);
    getNext(s, next, sLen);
    int minLen = sLen - next[sLen - 1];
    if(next[sLen - 1] != 0 && sLen % minLen == 0) return true;
    return false;
}

时间复杂度:O(n),空间复杂度:O(n)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值