View


😃 || 정리
문제에서 '첫 단어는 Enter, Leave, Change 중 하나이다.'
첫 단어를 조건으로 구분하기로 했다.
아이디와 닉네임 , key 값과 value 이렇게 떠올라서 Map을 쓰기로 했다.
그리고 배열에 저장할 값들을 일단 ArrayList에 저장한 후
ArrayList에 저장된 id 값을 닉네임으로 Replace하려고 했다. 👈 여기서부터 문제 발생

	public static void main(String[] args) {	
    	HashMap<String, String> resultMap = new HashMap<>();
        ArrayList<String> resultArr = new ArrayList<>();
        String[] arrRecord ;   
        for(int i=0; i<record.length; i++){
        	if(record[i].split(" ")[0].toUpperCase().equals("ENTER")){
                resultMap.put(record[i].split(" ")[1] , record[i].split(" ")[2]);
                resultArr.add(record[i].split(" ")[1] +"님이 들어왔습니다.");
            }else if (record[i].split(" ")[0].toUpperCase().equals("LEAVE")){
               resultArr.add(record[i].split(" ")[1] +"님이 나갔습니다.");
             System.out.println("leave msg : " + record[i].split(" ")[1] +"님이 나갔습니다.");
            }else if (record[i].split(" ")[0].toUpperCase().equals("CHANGE")){
                resultMap.put(record[i].split(" ")[1] , record[i].split(" ")[2]);
            }
        }
    	
      for(int i=0; i<resultArr.size(); i++){
        	for(String key : resultMap.keySet()){
        		if(resultArr.get(i).contains(key)){
        			System.out.println("bef msg : " + resultArr.get(i));
        			resultArr.set(i, resultArr.get(i).replace(key, resultMap.get(key)));
        			System.out.println("af msg : " + resultArr.get(i));
        			break;
        		}
        	}      	
        }
        
        String[] answer = resultArr.toArray(new String[0]);
    }

처음엔 이런식으로 코드를 짰다.
테스트케이스는 일단 성공했지만
성공률 32프로.. 출력이 틀렸다는 것도 있고 타임아웃도 발생했다.

알고보니 두 가지를 간과한 것
1. ENTER가 되지 않고 LEAVE가 먼저 찍힌 사용자가 존재 한다..
2. LEAVE가 먼저 출력된 사용자의 아이디가 uid999라고 하고 ,
다음사용자의 아이디가 uid99 , 닉네임이 MUZI 이면 uid999가 muzi9로 replace됨

key랑 value 값 잘 넣어뒀으면서
,, key값으로 찾읍시다~

😃 || 풀이 방법

import java.util.*;

class Solution {
    public String[] solution(String[] record) {
        HashMap<String, String> reㅃsultMap = new HashMap<>();
        ArrayList<String> resultArr = new ArrayList<>();
        String[] arrRecord ;  
        
        for(int i=0; i<record.length; i++){
            arrRecord = record[i].split(" ");
        	if(arrRecord.length > 2){
        		resultMap.put(arrRecord[1], arrRecord[2]);
        	}
        }
        
        for(int i=0; i<record.length; i++){
        	if(record[i].split(" ")[0].toUpperCase().equals("ENTER")){
                resultArr.add(resultMap.get(record[i].split(" ")[1]) +"님이 들어왔습니다.");
            }else if (record[i].split(" ")[0].toUpperCase().equals("LEAVE")){
                resultArr.add(resultMap.get(record[i].split(" ")[1]) +"님이 나갔습니다.");
            }
        }
        
        String[] answer = resultArr.toArray(new String[0]);
        
        return answer;
    }
}


Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31