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 <= 100s 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% 的用户

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

被折叠的 条评论
为什么被折叠?



