
Given a string s consisting only of characters a, b and c.
Return the number of substrings containing at least one occurrence of all these characters a, b and c.
코드 구성 논리는 문제없지만, 시간복잡도가 너무 높음.
class Solution {
public static int numberOfSubstrings(String s) {
int count = 0;
boolean a = false;
boolean b = false;
boolean c = false;
for (int i = 0; i < s.length(); i++) {
a = false;
b = false;
c = false;
for (int j = i; j < s.length(); j++) {
if (s.charAt(j) == 'a')
a = true;
if (s.charAt(j) == 'b')
b = true;
if (s.charAt(j) == 'c')
c = true;
if (a && b && c) {
count += s.length() - j;
break;
}
}
}
if (s.length() > 2)
return count; //+ numberOfSubstrings(s.substring(1));
else
return 0;
}
}
// right만 사용한 경우
class Solution {
public static int numberOfSubstrings(String s) {
int count = 0;
int[] lastSeen = {-1, -1, -1};
for (int i = 0; i < s.length(); i++) {
lastSeen[s.charAt(i) - 'a'] = i;
if (lastSeen[0] != -1 && lastSeen[1] != -1 && lastSeen[2] != -1) {
minIndex= count + Math.min(lastSeen[0], Math.min(lastSeen[1], lastSeen[2]));
count += minIndex + 1;
}
}
return count;
}
}
// left도 적용한 경우
class Solution {
public static int numberOfSubstrings(String s) {
int count = 0;
int[] freq = {0, 0, 0}; // 'a', 'b', 'c' 등장 횟수
int left = 0;
for (int right = 0; right < s.length(); right++) {
freq[s.charAt(right) - 'a']++; // 현재 문자의 개수 추가
// 'a', 'b', 'c'가 모두 포함되면 left를 이동
while (freq[0] > 0 && freq[1] > 0 && freq[2] > 0) {
count += s.length() - right; // 남은 길이 더하기
freq[s.charAt(left) - 'a']--; // left 이동 후 감소
left++;
}
}
return count;
}
}