hyelie
hyelie
Hyeil Jeong
       
글쓰기    관리    수식입력
  • 전체보기 (495)
    • PS (283)
      • Algorithm (28)
      • PS Log (244)
      • Contest (6)
      • Tips (5)
    • Development (52)
      • Java (14)
      • Spring (23)
      • SQL (2)
      • Node.js (2)
      • Socket.io (3)
      • Study (4)
      • Utils (4)
    • DevOps (36)
      • Git (5)
      • Docker (4)
      • Kubernetes (2)
      • GCP (3)
      • Environment Set Up (8)
      • Tutorial (12)
      • Figma (2)
    • CS (74)
      • OOP (7)
      • OS (24)
      • DB (2)
      • Network (24)
      • Architecture (0)
      • Security (2)
      • Software Design (0)
      • Parallel Computing (15)
    • Project (15)
      • Project N2T (5)
      • Project ASG (0)
      • Project Meerkat (1)
      • Model Checking (7)
      • Ideas (2)
    • 내가 하고싶은 것! (34)
      • Plan (16)
      • Software Maestro (10)
      • 취준 (8)
hELLO · Designed By 정상우.
hyelie

hyelie

PS/PS Log

23.04.12. 풀었던 문제들

Leetcode 71. Simplify Path

 이번 주는 stack 관련된 문제가 나오는 주인가보다. 계속 stack 문제가 나온다.

 일단 문제 조건은

  • directory 구분은 /로 한다. //와 같이, / 사이가 빈 경우에는 아무것도 하지 않는다.
  • .은 아무것도 하지 않는다
  • ..은 상위의 directory를 가리킨다.

 

 그러면 /를 delimiter로 사용해 parsing한 뒤, "."이나 ""가 나오면 아무것도 하지 않고 ".."가 나왔을 때만 stack에서 pop하면 될 것이다. 그리고 그 결과를 계산하면 될 것. 사실상 string parsing문제임을 알 수 있다. 기억하자. string parseing은 stringstream, buffer, delimiter, while(getline) 4개를 이용해 구할 수 있다.

// Runtime 8 ms Beats 46.38%
// Memory 9.3 MB Beats 70.22%

class Solution {
public:
    string simplifyPath(string path) {
        // parse by '/'
        vector<string> directories;
        istringstream iss(path);
        string buffer;
        while(getline(iss, buffer, '/')) directories.push_back(buffer);
        
        // use stack. pop and push.
        vector<string> canonical;
        for(string directory : directories){
            if(directory == "" || directory == ".") continue;
            else if(directory == ".."){
                if(!canonical.empty()) canonical.pop_back();
            }
            else canonical.push_back(directory);
        }

        string answer = "/";
        for(int i = 0; i<canonical.size(); i++){
            answer += canonical[i] + (i == canonical.size()-1 ? "" : "/");
        }
        return answer;
    }
};

 

시간복잡도

 string parsing에 path를 1번 순회, directories를 1번 순회, canonical을 1번 순회하므로 O(n)이다.

 

공간복잡도

 path size를 n이라고 했을 때, string vector directories, canonical, answer를 사용하는데 worst case O(n)의 크기를 가진다. 따라서 O(n).

 

 

 

 

 

 

저작자표시 (새창열림)

'PS > PS Log' 카테고리의 다른 글

23.04.14. 풀었둔 문제들  (0) 2023.04.14
23.04.13. 풀었던 문제들  (0) 2023.04.13
23.04.11. 풀었던 문제들  (0) 2023.04.11
23.04.10. 풀었던 문제들  (0) 2023.04.10
23.04.09. 풀었던 문제들  (0) 2023.04.09
    hyelie
    hyelie

    티스토리툴바