1876. Substrings of Size Three with Distinct Characters【字符串】
发布日期:2021-07-01 03:01:58 浏览次数:2 分类:技术文章

本文共 1216 字,大约阅读时间需要 4 分钟。

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: 1Explanation: 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: 4Explanation: 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% 的用户

转载地址:https://memcpy0.blog.csdn.net/article/details/117433883 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:1877. Minimize Maximum Pair Sum in Array【贪心/排序】
下一篇:1880. Check if Word Equals Summation of Two Words【字符串】

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月11日 03时49分52秒