변수 i로 탐색
cnt = 1로 초기화를 해준다. (가장 왼쪽부터 단어가 있기 때문에)
i == i+1과 비교를 하여 참이면 cnt를 증가시키고 거짓이면 answer에 단어를 누적을 시킨다. 그리고 cnt도 1일 경우엔 생략을 해야하므로 1보다 큰 경우에 String화 해서 answer에 누적시킨 후 작업이 완료되면 다시 cnt를 1로 초기화 시킨다.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public String solution(String s) {
String answer ="";
s = s + " "; //s 맨 뒤에 빈 문자 추가
int cnt = 1;
for (int i = 0; i < s.length()-1; i++) { //빈 문자 전까지만 가야하므로 s.length-1
if(s.charAt(i)==s.charAt(i+1)) cnt ++;
else {
answer += s.charAt(i);
if(cnt>1) answer += String.valueOf(cnt); //cnt가 String으로 형변환됨
cnt =1; //cnt는 다시 1로 초기화
}
}
return answer;
}
public static void main(String[] args){
Main T = new Main();
Scanner kb = new Scanner(System.in);
String str = kb.next();
System.out.println(T.solution(str));
}
}
'Algorithm > 문제' 카테고리의 다른 글
13. 큰 수 출력하기 (0) | 2023.05.29 |
---|---|
12.암호 (0) | 2023.05.25 |
10. 가장 짧은 문자거리 (0) | 2023.05.24 |
9. 숫자만 추출 (0) | 2023.05.23 |
8. 유효한 팰린드 롬 (0) | 2023.05.17 |