1876. Substrings of Size Three with Distinct Characters【字符串】

博客围绕字符串问题展开,若字符串无重复字符则为好字符串。要求计算给定字符串中长度为3的好子字符串数量,相同子串多次出现需重复计数。解法是遍历字符串,取三个连续字符,若都不相等则计数。

A string is good if there are no repeated characters.

Given a string s​​​​​, return the number of good substrings of length three in s​​​​​​.

Note that if there are multiple occurrences of the same substring, every occurrence should be counted.

A substring is a contiguous sequence of characters in a string.

Example 1:

Input: s = "xyzzaz"
Output: 1
Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". 
The only good substring of length 3 is "xyz".

Example 2:

Input: s = "aababcabc"
Output: 4
Explanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc".
The good substrings are "abc", "bca", "cab", and "abc".

Constraints:

  • 1 <= s.length <= 100
  • s​​​​​​ consists of lowercase English letters.

题意:如果一个字符串不含有任何重复字符,我们称这个字符串为  字符串。

给你一个字符串 s ,请你返回 s 中长度为 3 的 好子字符串 的数量。注意,如果相同的好子字符串出现多次,每一次都应该被记入答案之中。


解法 字符串

遍历字符串,每次取三个连续的字符,只要都不相等,就计算一次。

class Solution {
public:
    int countGoodSubstrings(string s) { 
        int ans = 0;
        for (int i = 0, n = s.size(); i <= n - 3; ++i)
            if (s[i] != s[i + 1] && s[i] != s[i + 2] && s[i + 1] != s[i + 2]) ++ans;
        return ans;
    }
};

运行效率如下:

执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗:6.1 MB, 在所有 C++ 提交中击败了20.00% 的用户
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

memcpy0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值