[LeetCode]로그파일 재정렬

Inhwan98·2023년 1월 8일
0

PTU STUDY_leetcode

목록 보기
3/24

문제

  • 로그를 재정렬하라. 기준은 다음과 같다.
  1. 로그의 가장 앞 부분은 식별자다.
  2. 문자로 구성된 로그가 숫자 로그보다 앞에 온다.
  3. 식별자는 순서에 영향을 끼치지 않지만, 문자가 동일한 경우 식별자 순으로 한다.
  4. 숫자 로그는 입력 순서대로 한다.
  • Example 1:
Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]
Explanation:
The letter-log contents are all different, so their ordering is "art can", "art zero", "own kit dig".
The digit-logs have a relative order of "dig1 8 1 5 1", "dig2 3 6".
  • Example 2:
Input: logs = ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]

코드

class Solution {
public:
    vector<string> reorderLogFiles(vector<string>& logs) {
        
    vector<string> result;

    int n = 0;

    for (int i = 0; i < logs.size(); i++)
    {
        n = logs[i].find(" ");
        if (isalpha(logs[i][n + 1]) != 0) result.push_back(logs[i]);
    }
    sort(result.begin(), result.end(), [](string& a, string& b)
        {
        int as = a.find(" ");
        int bs = b.find(" ");
        if (a.substr(as) == b.substr(bs)) return a.substr(0, as) < b.substr(0, as);
        return  a.substr(as) < b.substr(bs);
        });

    for (int i = 0; i < logs.size(); i++)
    {
        n = logs[i].find(" ");
        if (isdigit(logs[i][n + 1]) != 0) result.push_back(logs[i]);
    }

    return result;
    }
};

풀이

1.

 for (int i = 0; i < logs.size(); i++)
    {
    	//1.
        n = logs[i].find(" ");
        //2.
        if (isalpha(logs[i][n + 1]) != 0) result.push_back(logs[i]);
    }
    1. logs[i]에서 공백이 처음 시작하는 주소를 찾아 n에 대입.
    1. 첫공백은 항상 식별자 다음에 있기 때문에 n의 주소에서 +1을 해준다면 문자, 숫자로그를 찾을 수 있다. 문자로그는 별도의 정렬이 필요하고 숫자로그는 별도 정렬이 필요 없기때문에 먼저 문자로그를 찾아서 reult에 차례대로 push_back 해준다.

2.

//1.
sort(result.begin(), result.end(), [](string& a, string& b)
      {
      	//2.
      	int as = a.find(" ");
     		int bs = b.find(" ");
         	//3.
     		if (a.substr(as) == b.substr(bs)) return a.substr(0, as) < b.substr(0, as);
            //4.
     		return  a.substr(as) < b.substr(bs);
      });
    1. 문자로그들을 정렬 해주는데, sort함수에 람다식을 사용해서 특정 조건이 충족되면 정렬이 가능하게 한다.
    1. 먼저 a, b의 식별자를 구분하기 위해 첫번 째 공백 위치를 각각 as, bs에 담는다.
    1. 만약 a, b의 문자 로그가 같다면, 식별자 순으로 정렬 한다.
    1. 그렇지 않다면 문자로그의 크기로 정렬 한다.

3.

 for (int i = 0; i < logs.size(); i++)
    {
    	//1.
        n = logs[i].find(" ");
        //2.
        if (isdigit(logs[i][n + 1]) != 0) result.push_back(logs[i]);
    }
    1. n에 logs[i]의 공백이 처음 시작하는 주소를 넣는다.
    1. 식별자 다음에 로그가 숫자로그라면 result에 값을 추가한다.

결과

Runtime 11 ms / Memory 13.3 MB
https://leetcode.com/problems/reorder-data-in-log-files/submissions/879947683/


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

profile
코딩마스터

0개의 댓글