Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
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
Archives
Today
Total
관리 메뉴

hwooo

LeetCode (C/C++) 937. Reorder Data in Log Files 본문

Study/Algorithm

LeetCode (C/C++) 937. Reorder Data in Log Files

hwooo 2024. 6. 3. 17:17

https://leetcode.com/problems/reorder-data-in-log-files/description/

 

 


풀이

주어진 문자열을 공백 기준으로 잘라서 identifier와 주어진 문자열을 분리하여 저장한 후, Letter-logs만 주어진 기준으로 정렬했다. (문자열 기준 사전 순 정렬 후 동일하다면 식별자 기준으로 사전 순 정렬)

정렬된 순서로 Letter-logs 뒤에 Digit-logs를 붙여 반환하였다.


코드

class Solution {
typedef pair<string, string> ps;
public:
    vector<string> reorderLogFiles(vector<string>& logs) {
        vector<pair<string, ps>> let, dig;

        for (int i = 0; i < logs.size(); i++) {
            int j = 0;

            // ' ' 기준으로 identifier와 문자열 구분
            while (logs[i][j] != ' ')
                j++;
            string sub1 = logs[i].substr(0, j), sub2 = logs[i].substr(j);

            // Letter-logs와 Digit-logs 따로 저장
            // {원본 문자열, {identifiedr, 문자열}
            if (isdigit(logs[i][j + 1]))
                dig.push_back({logs[i], {sub1, sub2}});
            else
                let.push_back({logs[i], {sub1, sub2}});
        }

        // Letter-logs를 주어진 기준으로 정렬
        sort(let.begin(), let.end(), [](pair<string, ps> &a, pair<string, ps> &b) {
            if (a.second.second == b.second.second)
                return a.second.first < b.second.first;
            return a.second.second < b.second.second;
        });
        
        // 정렬된 문자열 담기
        vector<string> ans;
        for (int i = 0; i < let.size(); i++)
            ans.push_back(let[i].first);

        for (int i = 0; i < dig.size(); i++)
            ans.push_back(dig[i].first);

        return ans;
    }
};