알고리즘/문자열, 정렬
[알고리즘] 문자열 압축 with Java, 문자열에 빈 문자 하나 더해주기
VIPeveloper
2022. 2. 27. 15:48
728x90
반응형
오늘은 주말이니까 string파트는 다 끝낸다는 마인드로 강의를 수강해야겠다.
오늘 배운 것
1. 문자열에 빈 문자 하나 더해주기
문자열 전체를 순회하고 싶을 때, 빈 문자열을 하나 더해주는 포인트를 배웠다.
2. 문제 풀이
import java.util.Scanner;
public class Main {
public static String solution(String str){
String answer = "";
str +=" ";
char[] chars = str.toCharArray();
int cnt = 1;
for (int i = 0; i < chars.length-1; i++) {
if(chars[i] == chars[i+1]){
cnt++;
}else{
answer+=chars[i];
if(cnt!=1){
answer+=cnt;
}
cnt=1;
}
}
return answer;
}
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String str = kb.next();
System.out.println(solution(str));
}
}
728x90
반응형