原题链接在这里:https://leetcode.com/problems/unique-substrings-in-wraparound-string/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.
题解:
以题中"zab"为例. 以‘z‘为尾的最长连续substring长度是1. 只有一个substring "z".
以‘a‘为尾的最长连续substring长度是2. "za" 和 "a".
以‘b‘为尾的最长连续substring长度是3. "zab", "ab" 和 "b".
最长连续以这个letter 结尾的substring长度恰巧是max number of unique substring ends with这个letter.
如果后面有overlap也没有关系只要维护住最长的长度.
最后每个letter的max number of unique substring的和就是答案.
Time Complexity: O(p.length()). Space: O(1).
AC Java:
1 class Solution { 2 public int findSubstringInWraproundString(String p) { 3 int [] dp = new int[26]; 4 int maxCount = 0; 5 for(int i = 0; i<p.length(); i++){ 6 if(i>0 && (p.charAt(i)-p.charAt(i-1)==1 || p.charAt(i-1)-p.charAt(i)==25)){ 7 maxCount++; 8 }else{ 9 maxCount = 1; 10 } 11 12 dp[p.charAt(i)-‘a‘] = Math.max(dp[p.charAt(i)-‘a‘], maxCount); 13 } 14 15 int sum = 0; 16 for(int n : dp){ 17 sum += n; 18 } 19 return sum; 20 } 21 }