N

(Leet Code JS)Reorganize String 본문

Leet Code 알고리즘

(Leet Code JS)Reorganize String

naeunchan 2021. 11. 27. 20:30
728x90
반응형

https://leetcode.com/problems/reorganize-string/submissions/

 

Reorganize String - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

const asc = (a, b) => {
    if(a[1] === b[1]){
        return a[0] - b[0];
    }

    return b[1] - a[1];
}
    
const reorganizeString = (s) => {
    const map = new Map();
    const answer = [];
    let beforeChar = "";
    
    for(let i = 0; i < s.length; i++){
        const count = map.get(s[i]);
        
        map.set(s[i], count ? count + 1 : 1);
    }
    
    const orderedMap = [...map.entries()].sort(asc);
    
    console.log(orderedMap);
    
    while(orderedMap.length){
        let keep = false;
        
        for(let i = 0; i < orderedMap.length; i++){
            const [k, v] = orderedMap[i];
            
            if(beforeChar !== k){
                keep = true;
                answer.push(k);
                beforeChar = k;
                
                if(v - 1){
                    orderedMap[i][1] = v - 1;
                } else{
                    orderedMap.splice(i, 1);
                }
                break;
            }
        }
        
        if(!keep){
            return "";
        }
        
        orderedMap.sort(asc);        
    }
    
    return answer.join("");
};
728x90
반응형

'Leet Code 알고리즘' 카테고리의 다른 글

(Leet Code JS)Snapshot Array  (0) 2022.01.10
(Leet Code JS)Minesweeper  (0) 2021.12.21
(Leet Code JS)K Closest Points to Origin  (0) 2021.11.27
(Leet Code JS)Rearrange Words in a Sentence  (0) 2021.11.20
(Leet Code JS)Count and Say  (0) 2021.11.16