[LeetCode]#1876. Substrings of Size Three with Distinct Characters

Environment: Python 3.8

Key technique: for, if, !=

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".

Analysis:

Solution:

class Solution:
def countGoodSubstrings(self, s):
ans=0
for i in range(len(s)-2):
if (s[i] != s[i+1] and s[i] != s[i+2] and s[i+1] !=s[i+2]):
ans+=1
return ans

Submissions:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store