Leetcode/Top Interview 150

[Stack][Medium] 71. Simplify Path

자전거통학 2024. 5. 10. 04:07

https://leetcode.com/problems/simplify-path/description

 

Q. 주어진 / path 를 간단화한 방식으로 재정리 하라. 

 

 

Solution. 

 '/', '..' , '.' 등에 의한 operation 처리가 필요하다. 

 이때 이 operation의 바로 앞 path 를 처리하는 것이므로, 마지막 input path data가 필요하다. 

 따라서 stack style 자료구조가 필요. 

 

 역시 먼저 최대한 단순화 해 본다. 

 

  주어진 string에서 slash를 제외하고 단어를 뽑아 본다. 

  그리고 그 중에서 path name, operation 등을 구분하여 처리한다. 

 

 마지막으로 stack은 반대로 data가 쌓이므로, 이를 유의하여 최종 데이터를 만든다. 

 

더보기
public string SimplifyPath(string path) 
{
    string[] words = path.Split('/');
    Stack<string> buff = new Stack<string>();
    for(int q = 0; q < words.Length; ++q)
    {
        string cur = words[q];
        if(cur.Length == 0)
            continue;

        if(cur == "..")
        {
            if(buff.Count>0) buff.Pop();
        }
        else if(cur == ".")
        {
        	// do nothing.
        }
        else
            buff.Push(cur);
    }

    string ret = "";
    while(buff.Count > 0)
    {
        ret += Reverse(buff.Pop());
        ret += "/";
    }
    return ret.Length==0 ? "/" : Reverse(ret);
}

string Reverse(string str)
{
    return new string(str.Reverse().ToArray());
}

 

 

조금 느린 상태. 

뭐 여러 풀이가 있을 수 있겠다.