현재
11. 문자열 압축 본문
설명
반복되는알파벳만큼 압축해라
예시 입력 1
KKHSSSSSSSE
예시 출력 1
K2HS7E
예시 입력 2
KSTTTSEEKFKKKDJJGG
예시 출력 2
KST3SE2KFK3DJ2G2
<힌트>
더보기
- 길이에 주의할것!!
<자체풀이>
더보기
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
char strList[] = sc.next().toCharArray();
char temp = 32; // 32인경우 공백으로 알고있음
for(int i = 0 ; i < strList.length ; i++){
int duplicate = 1;
if(strList[i] != temp){
temp = strList[i];
for(int j = i; j < strList.length-1; j++){
if( strList[j+1] == temp){
duplicate++;
if( j+1 == strList.length-1 ){
i = j+1;
}
} else {
i = j;
break;
}
}
}
if(duplicate == 1){
System.out.print(strList[i]);
}else{
System.out.print(temp+""+duplicate);
}
}
//KKHSSSSSSSE
//K2HS7E
//KSTTTSEEKFKKKDJJGG
//KST3SE2KFK3DJ2G2
sc.close();
}
}
<정답코드>
더보기
import java.util.*;
class Main {
public String solution(String s){
String answer="";
s=s+" ";
int cnt=1;
for(int i=0; i<s.length()-1; i++){
if(s.charAt(i)==s.charAt(i+1)) cnt++;
else{
answer+=s.charAt(i);
if(cnt>1) answer+=String.valueOf(cnt);
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));
}
}
'알고리즘 > 기타알고리즘문제' 카테고리의 다른 글
| 소수(에라토스테네스 체) (0) | 2024.04.16 |
|---|---|
| 12. 암호 (0) | 2024.04.09 |
| 10. 가장 짧은 문자거리 (0) | 2024.04.08 |
| 8. 유효한 팰린드롬 (0) | 2024.04.03 |
| 7. 회문 문자열 (0) | 2024.04.03 |