[leetcode] 467. Unique Substrings in Wraparound String

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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

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", "b", "za", "ab", "zab" of string 
"zab" in the string s.

分析

题目的意思是:给定一个字符串,求出其不重复非空子字符串的个数。

  • 这里用了一个技巧,例如abcd字符串,以d结尾的子字符串有abcd, bcd,cd,d。bcd,cd,d都包含在abcd中,那么知道某个字符结束的最大字符串包含其他以该字符结束的字符串的字符串都包含在abcd中。
  • 题目就可以转换为分别求出以每个字符(a-z)为结束字符的最长连续字符串就行了,用一个数组cnt记录下来,最后在求出数组cnt的所有数字之和即为结果。

代码

class Solution {
public:
    int findSubstringInWraproundString(string p) {
        vector<int> cnt(26,0);
        int len=1;
        for(int i=0;i<p.length();i++){
            if(i>0&&(p[i]-p[i-1]==1||p[i-1]-p[i]==25)){
                len++;
            }else{
                len=1;
            }
            cnt[p[i]-'a']=max(cnt[p[i]-'a'],len);
        }
        return accumulate(cnt.begin(),cnt.end(),0);
    }
};

参考文献

[LeetCode] Unique Substrings in Wraparound String 封装字符串中的独特子字符串

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值