LeetCode 题解(Week 10): 467. Unique Substrings in Wraparound String

原题目

Consider the string s to be the infinite wraparound string of “abcdefghijklmnopqrstuvwxyz”, so s will look like this: “…zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv xyzabcd….”.

Now we have another string p. Your job is to find out how many unique non-empty substrings of p are present in s. In particular, your input is the string p and you need to output the number of different non-empty substrings of p in the string s.

Note: p consists of only lowercase English letters and the size of p might be over 10000.

Example 1:

Input: “a”
Output: 1 Explanation: Only the substring “a” of string “a”
is in the string s.

Example 2:

Input: “cac”
Output: 2 Explanation: There are two substrings “a”, “c”
of string “cac” in the string s.

Example 3:

Input: “zab”
Output: 6 Explanation: There are six substrings “z”, “a”,

中文大意

假设s是一个按照字母顺序无限循环的字符串,给定另一个有限的普通字符串p(其中字符都是小写英文),问同时在p与s中的子串有多少个?(这里的子串是连续子串,好坑,题目没有讲)

题解

class Solution {
public:
    int findSubstringInWraproundString(string p) 
    {
        if(p.empty()) return 0;

        vector<int> letter(26,0);
        vector<int> sub(p.size(),0);

        sub[0] = 1;
        letter[p[0]-'a'] = 1;

        for(int i = 1 ;i < p.size(); i ++)
        {
            if( p[i] - p[i-1] == 1 || p[i] - p[i-1] == -25 )
                 sub[i] += sub[i-1];
            sub[i] ++;

            int ind = p[i] - 'a';
            letter[ind] = max(letter[ind],sub[i]);
        }

        int sum = 0;
        for(int i=0; i < letter.size() ; i ++)
        {
            // cout << letter[i];
            sum += letter[i];
        }
        return sum;
    }
};

分析:

这道题看题目就知道必须要在O(n)的时间复杂度下解决战斗(因为说明了p的长度是有可能超过10000的,这个时候n^2就没法玩了),由于是求不同的子串,那这就有一个线索:比如字符串ababa,那有2个ab子串是重复的,但其实以不管子串所在的位置,我们只要算出,以b为结尾的子串有3个(a,b,ab)就可以了,然后我们只需要记住以b结尾的最长子串,这样就能够起到一个去重的作用。所以用一个26长度的数组,记录以每一个字母结尾的子串的最长长度,最终的答案就是这个数组的和。

此外,需要用到一个与p同样长度的整形数组,来记录下p[i]结尾的子串个数,这个子串个数是可以通过动态规划算出来的:如果当前的字符能够与上一个字符接起来,那当前的子串个数就是上一个字符结尾的子串个数+2,否则为1,最终,根据当前的结果来对上一段所说的数组来进行更新。

这样做的时间复杂度为O(n),空间复杂度为O(n)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值