467. 环绕字符串中唯一的子字符串https://leetcode.cn/problems/unique-substrings-in-wraparound-string/
把字符串 s 看作 "abcdefghijklmnopqrstuvwxyz" 的无限环绕字符串,所以 s 看起来是这样的:
"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...." 。
现在给定另一个字符串 p 。返回 s 中 不同 的 p 的 非空子串 的数量 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/unique-substrings-in-wraparound-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
简单dp,dp[α] 表示p中以字符 α 结尾且在 s 中的子串的最长长度
class Solution {
public:
string p;
int l;
bool isadj(int i)
{
if (i >= l)
return false;
return (p[i] == 'z' && p[i + 1] == 'a') || p[i] + 1 == p[i + 1];
}
int findSubstringInWraproundString(string tp) {
p = tp;
l = tp.length();
int dp[30];
memset(dp, 0, sizeof(dp));
int len = 1;
for (int i = 0; i < l; i++)
{
if (dp[p[i] - 'a'] < len)
dp[p[i] - 'a'] = len;
len = isadj(i) ? len + 1 : 1;
}
int ans = 0;
for (int i = 0; i < 26; i++)
ans += dp[i];
return ans;
}
};