[Programmers] [3차] 압축 - 2018 KAKAO BLIND RECRUITMENT

동민·2021년 3월 11일
0
import java.util.ArrayList;

// [3차] 압축 - 2018 KAKAO BLIND RECRUITMENT
public class Compression {
	public int[] solution(String msg) { // startsWith(), indexOf() 활용

		ArrayList<String> dictionary = new ArrayList<>(); // 사전 리스트
		ArrayList<Integer> result = new ArrayList<>(); // 색인 번호를 저장할 리스트
		StringBuilder sb = new StringBuilder(msg);

		for (char i = 'A'; i <= 'Z'; i++) {
			dictionary.add(i + "");
		}

		while (sb.length() != 0) {
			for (int i = dictionary.size() - 1; i >= 0; i--) {

				String str = dictionary.get(i);
				if (sb.toString().startsWith(str)) { // StringBuilder 클래스는 접두사를 찾는 startsWith() 메소드가 정의되어있지 않으므로 sb.toString()으로 String클래스로 변환 후 startsWith() 메소드 사용
					result.add(dictionary.indexOf(str) + 1); // indexOf() 메소드를 통해 색인 번호 저장
					sb.delete(0, str.length());
					if (sb.length() != 0) {
						dictionary.add(str + sb.charAt(0) + "");
					}
					break;
				}

			}
		}

		return result.stream().mapToInt(i -> i.intValue()).toArray();
	}
}
String 클래스의 startsWith() 메소드 활용 - 접두사 찾는 메소드
startsWith() : 접두사
endsWith() : 접미사
profile
BE Developer

0개의 댓글

관련 채용 정보