动态规划-独特的子字符串存在于Wraparound String总个数 Unique Substrings in Wraparound String

Posted hyserendipity

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态规划-独特的子字符串存在于Wraparound String总个数 Unique Substrings in Wraparound String相关的知识,希望对你有一定的参考价值。

2018-09-01 22:50:59

问题描述:

问题求解:

如果单纯的遍历判断,那么如何去重保证unique是一个很困难的事情,事实上最初我就困在了这个点上。

后来发现是一个动态规划的问题,可以将每个字符结尾的最长长度进行保存,这样就巧妙的解决的重复的问题。

  1. The max number of unique substring ends with a letter equals to the length of max contiguous substring ends with that letter. Example "abcd", the max number of unique substring ends with \'d\' is 4, apparently they are "abcd", "bcd", "cd" and "d".
  2. If there are overlapping, we only need to consider the longest one because it covers all the possible substrings. Example: "abcdbcd", the max number of unique substring ends with \'d\' is 4 and all substrings formed by the 2nd "bcd" part are covered in the 4 substrings already.
  3. No matter how long is a contiguous substring in p, it is in s since s has infinite length.
  4. Now we know the max number of unique substrings in p ends with \'a\', \'b\', ..., \'z\' and those substrings are all in s. Summary is the answer, according to the question.
    public int findSubstringInWraproundString(String p) {
        int res = 0;
        int[] dp = new int[26];
        int maxLen = 0;
        for (int i = 0; i < p.length(); i++) {
            if (i > 0 && (p.charAt(i) - p.charAt(i - 1) == 1 || p.charAt(i - 1) - p.charAt(i) == 25)) {
                maxLen++;
            }
            else maxLen = 1;
            dp[p.charAt(i) - \'a\'] = Math.max(dp[p.charAt(i) - \'a\'], maxLen);
        }
        for (int i = 0; i < 26; i++) res += dp[i];
        return res;
    }

 

以上是关于动态规划-独特的子字符串存在于Wraparound String总个数 Unique Substrings in Wraparound String的主要内容,如果未能解决你的问题,请参考以下文章

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

leetcode-5 最长回文子串(动态规划)

算法导论-动态规划学习笔记day01

动态规划不同的子序列

动态规划专题

动态规划(dp)----公共子序列(LCS) 问题进一步理解