문제 링크 : https://www.acmicpc.net/problem/2941
package Boj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class boj_2941 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int resultLength = 0;
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) == 'c' && i < str.length() - 1) {
if (str.charAt(i + 1) == '=') {
i++;
}
else if (str.charAt(i + 1) == '-') {
i++;
}
}
if(str.charAt(i) == 'd' && i < str.length() - 1) {
if(str.charAt(i + 1) == 'z') {
if(i < str.length() - 2) {
if (str.charAt(i+2) == '=' ) {
i += 2;
}
}
if(str.charAt(i+1) == '-') {
i++;
}
}
}
if (str.charAt(i) == 'l' && i < str.length() - 1) {
if(str.charAt(i + 1) == 'j') {
i++;
}
}
if (str.charAt(i) == 'n' && i < str.length() - 1) {
if(str.charAt(i + 1) == 'j') {
i++;
}
}
if (str.charAt(i) == 's' && i < str.length() - 1) {
if(str.charAt(i + 1) == '=') {
i++;
}
}
if (str.charAt(i) == 'z' && i < str.length() - 1) {
if(str.charAt(i + 1) == '=') {
i++;
}
}
resultLength++;
}
br.close();
System.out.println(resultLength);
}
}
2번째 풀이 방식
자바 String API를 사용하기
이 방법은 전에 이것을 풀 때, String.contains()를 사용해 볼려 했으나,
어떻게 하는 지 감이 안잡힌다.
그래도 한번 써보자
package Boj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class boj_2941 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
br.close();
String[] croatiaAlphabet = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};
// 알파벳 목록을 귀찮게 일일히 if문을 쓰지말고
int count = 0;
for(String val : croatiaAlphabet) {
while(str.contains(val)) { //포함되어있으면
str = str.replace(val, "A"); //하나의 글자로 세기로 했던 문제 규칙을 지키게 하기
}
}
count += str.length();
System.out.println(count);
}
}
해당 코드로 하니까 정답이 나왔다.
이제 반례에 대해서 정리해보자