链接:https://leetcode.cn/problems/count-unique-characters-of-all-substrings-of-a-given-string/solution/by-xun-ge-v-a7p1/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


解题思路
【动态规划】
定义sum为以当前字符结尾的字符串的唯一字符之和。
当遍历到第k个字符时,有三种情况:
【数学思维】
- /*
- MOST_CHARS: 共26个大写字母。
- INIT_POSITION: 假想字符串最左端,即下标-1处有一个虚拟的相同字符。
- x: 循环下标。
- length: 字符串长度。
- ch: 字母表中的顺序,A对应0,B对应1,C对应2,……,Z对应25。
- result: 结果值。题目保证不会越界int类型。
- near[26]: 每个字符左侧离它最近的下标位置。
- farther[26]: 每个字符左侧离它第二近的下标位置。
- */
-
- #define MOST_CHARS 26
- #define INIT_POSITION -1
-
- int uniqueLetterString(char *s)
- {
- int x = 0, length = 0, ch = 0, result = 0;
- int farther[MOST_CHARS], near[MOST_CHARS];
-
- /* 初始化为-1。 */
- memset(farther, INIT_POSITION, sizeof(farther));
- memset(near, INIT_POSITION, sizeof(near));
-
- /* 遍历一趟字符串。 */
- while('\0' != s[x])
- {
- /* 当前字符在字母表中的顺序。 */
- ch = s[x] - 'A';
- /* 如果near[ch]不等于-1,表示非第一次出现,此时,它左侧的那个相同字符即可计算其贡献值了。 */
- if(INIT_POSITION != near[ch])
- {
- result += (x - near[ch]) * (near[ch] - farther[ch]);
- }
- /* 更新near和farther。 */
- farther[ch] = near[ch];
- near[ch] = x;
- x++;
- }
-
- /* 字符串遍历到结束符时,x值就等于字符串长度length。 */
- length = x;
-
- /* 最后一个字符的贡献值。 */
- x = 0;
- while(MOST_CHARS > x)
- {
- /* 不等于-1时,才说明这个字符是存在过的。
- 等于-1的话,则表示这个字符在字符串中从头到尾没有出现过。 */
- if(INIT_POSITION != near[x])
- {
- result += (length - near[x]) * (near[x] - farther[x]);
- }
- x++;
- }
-
- return result;
- }
-
-
- 作者:xun-ge-v
- 链接:https://leetcode.cn/problems/count-unique-characters-of-all-substrings-of-a-given-string/solution/by-xun-ge-v-a7p1/
- 来源:力扣(LeetCode)
- 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
【动态规划】
- #define MOD 1000000007
- int uniqueLetterString(char *str) {
- int at1[26] = { 0 }, at2[26] = { 0 }, sum = 0, ans = 0;
-
- for (int i = 0; str[i]; ++i) {
- int pos = str[i] - 'A';
- sum += i + 1 - 2 * at1[pos] + at2[pos];
- ans += sum, ans %= MOD;
-
- at2[pos] = at1[pos], at1[pos] = i + 1;
- }
-
- return ans;
- }
-
-
-
- 作者:xun-ge-v
- 链接:https://leetcode.cn/problems/count-unique-characters-of-all-substrings-of-a-given-string/solution/by-xun-ge-v-a7p1/
- 来源:力扣(LeetCode)
- 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。