https://www.acmicpc.net/problem/31882
(count * (count + 1)) / 2
의 공식을 사용해 부분 문자열 길이의 합을 구할 수 있습니다.
import java.io.*;
import java.util.HashMap;
public class Main {
// input
private static BufferedReader br;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
bw.write(solve());
bw.close();
} // End of main()
private static String solve() throws IOException {
StringBuilder sb = new StringBuilder();
int N = Integer.parseInt(br.readLine());
String S = br.readLine();
int count = 0;
long sum = 0;
for (int i = 0; i < N; i++) {
char ch = S.charAt(i);
if (ch == '2') {
count++;
} else {
count = 0;
}
sum += (long) count * (count + 1) / 2;
}
sb.append(sum);
return sb.toString();
} // End of solve()
} // End of Main class