본문 바로가기
LeetCode

[LeetCode] 71. Simplify Path

by 콩순이냉장고 2023. 8. 29.

문제 URL : https://leetcode.com/problems/simplify-path/

 

Simplify Path - LeetCode

Can you solve this real interview question? Simplify Path - Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path. In a Unix-style file sys

leetcode.com

 

문제 접근법 : 

 

구현문제입니다. 

/ or //는 /로 처리하고

.은 현재 디렉터리 ..은 상위 디렉터리에 가라는뜻인데

 

결국엔 stack를 이용하면 쉽게풀립니다.

그치만 stack보단 전 vector를 이용했고 오히려 문제 조건에 있는것의처리 하는것이 관건인데

regex를 이용하면 빠르게 처리할수있습니다.

 

소스코드 : 

 

 

class Solution {
public:
vector<string> split(string &s,string pattern=" "){
    regex re(pattern);
    sregex_token_iterator it(s.begin(),s.end(),re,-1),end;
    return vector<string>(it,end);
}

string simplifyPath(string path) {
    vector<string> v = split(path,R"(/+)");
    vector<string> rv;
    for(string &s:v){
        if(s=="."||s=="")continue;
        else if(s==".."){
            if(!rv.empty())rv.pop_back();
        }
        else{
            rv.push_back(s);
        }
    }
    string res="/";
    for(string &s:rv)res+=s+"/";
    if(res.size()>1)res.pop_back();
    return res;
}
};

 

 

궁금한점 혹은 모르는점 어떤질문이든 댓글은 언제나 환영입니다.

 

'LeetCode' 카테고리의 다른 글

[LeetCode] 37. Sudoku Solver  (0) 2023.08.31
[LeetCode] 146. LRU Cache  (0) 2023.08.31
[LeetCode] 139. Word Break  (0) 2023.08.28
[LeetCode] 140. Word Break II  (0) 2023.08.28
[LeetCode] 126. Word Ladder II  (0) 2023.08.28