21.05.15 기록
-
백준 알고리즘 8958 풀이 완료
- 내가 푼 8958 풀이 (메모리 14.6MB, 시간 136ms로 통과)
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class B8958 { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); try { int testCase = Integer.parseInt(br.readLine()); String[] arrStr = new String[testCase]; for(int i = 0; i < testCase; i++) { arrStr[i] = br.readLine(); int cnt = 0; int score = 0; for(int j = 0; j < arrStr[i].length(); j++) { if(arrStr[i].charAt(j) == 'O') { cnt++; } else { cnt = 0; } score += cnt; } sb.append(score).append("\n"); } System.out.println(sb); } catch (IOException e) { e.printStackTrace(); } } }
- 아래는 찾아본 다른 풀이이다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class B8958 {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
try {
int testCase = Integer.parseInt(br.readLine());
for(int i = 0; i < testCase; i++) {
int cnt = 0;
int score = 0;
for(byte b : br.readLine().getBytes(StandardCharsets.UTF_8)) {
if (b == 'O') {
cnt++;
score += cnt;
} else cnt = 0;
}
sb.append(score).append("\n");
}
System.out.println(sb);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- getBytes(UTF_8)은 UTF_8 형식의 문자열을 바이트 배열로 반환한다.
- 반환받은 바이트 배열의 각 요소(byte b)를 꺼내어 ‘O’와 같은지 비교 후 연산을 처리하는 로직이다.