import java.util.*;
import java.util.stream.*;
class Solution {
int ansIdx = 1; // 람다식의 경우 지역변수는 참조할 수없다( 람다식이 실행되는 스레드와 지역변수가 있는 스레드가 다를수있음) 지역변수가 로딩되는 스택은 스레드 마다 할당되므로
// 따라서 클래스의 필드나 final 로 선언한 배열안에둔 원소를 인덱스 참조 하여 사용할 것
public int[] solution(String msg) {
String[] msgData = msg.split(""); // 문자 단위로 스플릿
Map<String,Integer> map = new HashMap<>();
// int -> char ,char -> int 캐스팅 가능하다.
IntStream.rangeClosed((int) 'A',(int) 'Z')
.forEach(n -> {
map.put(String.valueOf((char) n), ansIdx++);
});
List<Integer> ans = new ArrayList<>();
StringBuilder accKey = new StringBuilder();
int curIdx=0;
boolean flag = false;
while(curIdx < msgData.length) {
if(curIdx == msgData.length-1){
ans.add(map.get(msgData[curIdx]));
break;
}
accKey.append(msgData[curIdx]);
// 아직 등록되지 않은 단어가 나올때 까지 계속해서 키 값 누적하여 갱신한다.
while(map.containsKey(accKey.toString()) && curIdx < msgData.length){
// 마지막까지 등록된 키이면 그대로 답에 넣어주고 탈출
if(curIdx+1 == msgData.length) {
String finalKey = accKey.toString();
ans.add(map.get(finalKey));
flag=true;
break;
}
accKey.append(msgData[++curIdx]);
}
if(flag) break;
// 현재 등록되지 않은 키가 나온 경우이다. 등록해주고 이전까지 갱신되었던 (이미 등록된 키)를 답으로 넣어줌
else{
String newKey = accKey.toString();
ans.add(map.get(newKey.substring(0,newKey.length()-1)));
map.put(newKey,ansIdx++);
accKey.setLength(0);
}
}
/*
Map 자료형 스트림으로 하기 위해서는 entrySet().stream()으로 스트림 반환
map.entrySet().stream().forEach(e ->{
System.out.println(e.getKey()+" "+e.getValue());
});
*/
int[] answer = ans.stream().mapToInt(Integer::intValue).toArray();
return answer;
}
}