【Leetcode】828. Count Unique Characters of All Substrings of a Given String

题目地址:

https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/description/

给定一个长 n n n的全是大写英文字母的字符串 s s s,设其某个子串为 t t t f ( t ) f(t) f(t) t t t中只出现 1 1 1次的字母个数,求 ∑ t f ( t ) \sum_t f(t) tf(t) t t t遍历 s s s的所有子串。

我们直接看每个字母对于答案的贡献是多少,即问对于 s [ i ] s[i] s[i],其在多少个子串里是只出现了一次,那么我们就看其最近左边出现的位置和最近右边出现的位置,左右延伸长度的乘积即为其贡献。最后求总和即可。代码如下:

class Solution {
 public:
  int uniqueLetterString(string s) {
    int cur[26], pre[26];
    memset(cur, -1, sizeof cur);
    memset(pre, -1, sizeof pre);

    int res = 0;
    for (int i = 0; i < s.size(); i++) {
      int idx = s[i] - 'A';
      res += (i - cur[idx]) * (cur[idx] - pre[idx]);
      pre[idx] = cur[idx];
      cur[idx] = i;
    }

    for (int i = 0; i < 26; i++) res += (s.size() - cur[i]) * (cur[i] - pre[i]);
    return res;
  }
};

时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值