Coding Test/LeetCode

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

owls 2022. 12. 27. 20:03
728x90
  • 문제

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.

substring is a contiguous sequence of characters in a string.

 

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

 

  • 문제 해결
class Solution {
public:
    int countGoodSubstrings(string s) {
        
        if(s.size()<3)return 0;
        char a=s[0],b=s[1],c=s[2];
        int res=0;
        for(int i=3;i<=s.size()-1;i++)
        {
            if(a!=b and b!=c and c!=a)res++;
            a=b;
            b=c;
            c=s[i];
        }
        if(a!=b and b!=c and c!=a)res++;
        return res;
    }
};

 

다른 풀이

class Solution {
public:
    int countGoodSubstrings(string s) {
        
        if(s.size() < 3){
            return 0;
        }
        
        int result = 0;
        
        map<char, int> m;        
        for(int i = 0; i <= s.size()-3; i++){
            m[s[i]]++;
            m[s[i+1]]++;
            m[s[i+2]]++;
            if(m.size() == 3){
                result++;
            }
            m.clear();
        }
        
        return result;
    }
};

 

728x90