LeetCode467. Unique Substrings in Wraparound String——动态规划

一、题目

We define the string base to be the infinite wraparound string of “abcdefghijklmnopqrstuvwxyz”, so base will look like this:

“…zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd…”.
Given a string s, return the number of unique non-empty substrings of s are present in base.

Example 1:

Input: s = “a”
Output: 1
Explanation: Only the substring “a” of s is in base.
Example 2:

Input: s = “cac”
Output: 2
Explanation: There are two substrings (“a”, “c”) of s in base.
Example 3:

Input: s = “zab”
Output: 6
Explanation: There are six substrings (“z”, “a”, “b”, “za”, “ab”, and “zab”) of s in base.

Constraints:

1 <= s.length <= 105
s consists of lowercase English letters.

二、题解

class Solution {
public:
    int findSubstringInWraproundString(string s) {
        int n = s.size();
        vector<int> a(n,0);
        for(int i = 0;i < n;i++){
            a[i] = s[i] - 'a';
        }
        //dp[0]代表s中以a结尾的子串,最大延伸长度是多少(根据base串规则)
        vector<int> dp(26,0);
        dp[a[0]] = 1;
        int len = 1;
        for(int i = 1;i < n;i++){
            int cur = a[i],pre = a[i-1];
            if((pre == 25 && cur == 0) || pre == cur - 1) len++;
            else len = 1;
            dp[cur] = max(dp[cur],len);
        }
        int res = 0;
        for(int i = 0;i < 26;i++){
            res += dp[i];
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值