[첫번째 생각]
ddz=z=의 경우, (d) (dz=) (z=)
ljes=njnk의 경우, (lj) (e) (s=) (nj) (n) (k) 로 끊어져서 개수를 셀 수 있다.
그렇다면 어떻게 저렇게 끊을 수 있을까 고려해보았다.
[문제점 발생]
표에 나오지 않은 것들이 일반적이라면
표에 나온 특별한 경우를 생각했다.
특별한 경우만 알 수 있다면 문제를 해결 할 수 있을 것 같았다.
따라서, 케이스분류를 했다.
c 가 나오고 나면 '=' '-'
d가 나오고 나면 'z=' '='
l 혹은 n이 나오고 나면 'j'
s 혹은 z가 나오고 나면 '='
이를 스위치 문에 모든 케이스를 정리했다.
[두번째 생각]
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine().trim();
int count = 0;
int length = str.length();
int i;
for(i = 0; i < length; i++) {
count++;
switch(str.charAt(i)) {
case'c':
if(i < length - 1 && (str.charAt(i + 1)== '=') || (str.charAt(i + 1)== '-')) {
i++;
}
break;
case'd':
if(i < length - 2 && (str.charAt(i + 1)== 'z') && (str.charAt(i + 2)== '=')) {
i+=2;
} else if(i < length - 1 && (str.charAt(i + 1) == '-') ) {
i++;
}
break;
case'l':case'n':
if(i < length - 1 && (str.charAt(i + 1) == 'j')) {
i++;
}
break;
case's':case'z':
if(i < length - 1 && (str.charAt(i + 1) == '=')) {
i++;
}
break;
}
}
System.out.println(count);
}
}
[문제발생1]
case'c':
if(i < length - 1 && (str.charAt(i + 1)== '=') || (str.charAt(i + 1)== '-')) {
i++;
}
break;
만약, ABC를 입력한다고 가정하자.
C가 마지막에 있기때문에 if(i<length- 1 && (str.charAt(i+ 1)=='=') || (str.charAt(i+ 1)=='-')) 이 코드가 실행되는데
i < length - 1을 만족하지 않더라도 뒤에 str.charAt(i + 1)은 실행이 된다. 따라서 인덱스문제가 발생한다.
이를 해결하기 위해서는 아래와 같이 코드를 바꿔줘서 순서대로 확인하게 하면 된다.
case'c':
if(i < length - 1){
if( (str.charAt(i + 1)== '=') || (str.charAt(i + 1)== '-')) {
i++;
}
}
break;
[문제발생2]
if(i < length - 2) {
if((str.charAt(i + 1)== 'z') && (str.charAt(i + 2)== '=')) {
i+=2;
}
}
if(i < length - 1) {
if((str.charAt(i + 1)== '-')) {
System.out.println("d_executed2");
i++;
}
}
처음에는 이 코드를 if후에 else if를 두었다.
따라서 앞의 if문이 만족되는 경우에는 뒤의 else if문이 실행되지 않는 것이다.
왜냐하면 앞에 문이 부정돼야지 뒤에 문이 시작되기때문이다.
그런데, d-e의 경우에는 앞의 if문을 들어갔다가 만족하지 못해서 else if로 들어가야하는데
들어가질 못하니 count가 3이 나왔다.
[결론]
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine().toLowerCase();
int count = 0;
int length = str.length();
int i;
for(i = 0; i < length; i++) {
count++;
switch(str.charAt(i)) {
case'c':
if(i < length - 1){
if( (str.charAt(i + 1)== '=') || (str.charAt(i + 1)== '-')) {
i++;
}
}
break;
case'd':
if(i < length - 2) {
if((str.charAt(i + 1)== 'z') && (str.charAt(i + 2)== '=')) {
i+=2;
}
}
if(i < length - 1) {
if((str.charAt(i + 1)== '-')) {
i++;
}
}
break;
case'l':case'n':
if(i < length - 1) {
if(str.charAt(i + 1) == 'j') {
i++;
}
}
break;
case's':case'z':
if(i < length - 1) {
if(str.charAt(i + 1) == '=') {
i++;
}
}
break;
default: break;
}
}
System.out.println(count);
sc.close();
}
}
'이제는 사용하지 않는 공부방 > Algorithm' 카테고리의 다른 글
[백준] 섬의 개수 (0) | 2020.09.15 |
---|---|
[프로그래머스] 완전탐색문제: 모의고사 (0) | 2020.09.09 |
백준 8단계 다이얼 자바 (0) | 2020.04.18 |
백준 8단계 상수 자바 (0) | 2020.04.18 |
백준 8단계 단어의 개수 (0) | 2020.04.18 |