반응형
    
    
    
  코딩도장 - 문자열 압축하기

import java.util.Scanner;
public class StringZip {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("문자를 입력하세요");
		String word = sc.nextLine();
		System.out.println(zip(word));
		sc.close();
	}
	public static String zip(String compress) {
		String result = "";
		int count = 1;
		for (int i = 0; i < compress.length() - 1; i++) {
			if (compress.charAt(i) == compress.charAt(i + 1)) { //앞뒤 문자 같을때
				count++;	// 카운트
			} else if (compress.charAt(i) != compress.charAt(i + 1)) {	// 앞뒤 문자가 다를때
					result += compress.charAt(i) + Integer.toString(count);	//문자+카운트 더하기
					count = 1;	// 카운트 초기화
//				if(compress.length()-2==i) {	
//					result += compress.charAt(i + 1) + Integer.toString(count);	//마지막 문자 출력
//				}
			} 
		}
        result += compress.charAt(compress.length()-1) + String.valueOf(count);	//마지막 문자 출력 for종료후..
//      result += compress.charAt(compress.length()-1) + Integer.toString(count);	//마지막 문자 출력 for종료후..
		return result;
	}
}
코드가 너무 난잡하네... 반성반성
char 배열 넣은 후 비교
import java.util.Scanner;
public class StringZip {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("문자를 입력하세요");
		String word = sc.nextLine();
		System.out.println(zip(word));
		sc.close();
	}
	public static String zip(String compress) {
		String result = "";
		char[] word = compress.toCharArray();	// word 배열에 compress문자열 저장
		char buf = word[0];	//초기값 셋팅
		int count = 0;	카운트
		for(int i = 0; i < word.length; i++) {	// word 배열끝까지
			if(word[i]==buf) {
				count++;	//동일 단어 카운트
			}
			else {
				result += buf+Integer.toString(count);	// result에 저장
				buf=word[i];	//buf값 변경
				count=1;		//카운트 초기화
			}
		}
		result += buf+Integer.toString(count);	// 마지막 문자 출력		
		return result;
	}
}
https://codingdojang.com/scode/465
코딩도장
프로그래밍 문제풀이를 통해서 코딩 실력을 수련
codingdojang.com
반응형
    
    
    
  '알고리즘 > 코딩도장' 카테고리의 다른 글
| 가~위 바위~ 보! (0) | 2021.05.31 | 
|---|---|
| 구글 입사 문제 중에서 (0) | 2021.05.28 | 
| CamelCase를 Pothole_case로 바꾸기! (0) | 2021.05.28 | 
| 모스부호 해독 (0) | 2021.05.28 | 
| 타노스의 핑거 스냅 (0) | 2021.05.28 |