-
[LeetCode] 1876. Substrings of Size Three with Distinct Characters c++Coding Test/LeetCode 2022. 12. 27. 20:03728x90
- 문제
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.
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'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 695. Max Area of Island c++ (0) 2022.12.28 [LeetCode] 733. Flood Fill c++ (0) 2022.12.28 [LeetCode] 567. Permutation in String c++ (0) 2022.12.27 [LeetCode] 3. Longest Substring Without Repeating Characters c++ (0) 2022.12.27 [LeetCode] 19. Remove Nth Node From End of List c++ (0) 2022.12.27