https://leetcode.com/problems/unique-substrings-in-wraparound-string/description/
解题思路:
- 对于abc求它们的unique:dp[i] = dp[i - 1] + 1; 然后sum(all dp[i])
- 对于这个题dp[0-25] represents a-z的长度;然后sum所有。如果有两个b,分别计算其长度,然后选取其中最大的那个。
代码:
class Solution {
public int findSubstringInWraproundString(String p) {
int[] dp = new int[26];
int curLength = 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))){
curLength++;
} else{
curLength = 1;
}
int index = p.charAt(i) - 'a';
dp[index] = Math.max(dp[index], curLength);
}
int sum = 0;
for(int i = 0; i < 26; i++){
sum += dp[i];
}
return sum;
}
}
网友评论