hwooo
LeetCode (C/C++) 937. Reorder Data in Log Files 본문
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;
}
};
'Study > Algorithm' 카테고리의 다른 글
| LeetCode (C/C++) 86. Partition List (0) | 2024.06.04 |
|---|---|
| LeetCode (C/C++) 1710. Maximum Units on a Truck (0) | 2024.06.03 |
| LeetCode (C/C++) 209. Minimum size Subarray Sum (0) | 2024.06.01 |
| LeetCode (C/C++) 36. Valid Sudoku (0) | 2024.05.29 |
| LeetCode (C/C++) 452. Minimum Number of Arrows to Burst Balloons (0) | 2024.05.29 |