0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

71. Simplify Path 解答例・ポイント

Posted at

問題内容

与えられた絶対パスを決められたルールに従って書き直す

解答例

sample
class Solution:
    def simplifyPath(self, path: str) -> str:
        components = path.split("/")
        st = []

        for comp in components:
            if comp == "" or comp == ".":
                continue
            
            if comp == "..":
                if st:
                    st.pop()
            else:
                st.append(comp)
        
        return "/" + "/".join(st)

この問題のポイント

この問題では、決められたルールに従うため複数の条件を設定しなければならず、その方法を考えるのが難しさにつながっている。
解答例では、最初から戻り値を作っていくのではなく、一度リストに保管しながら条件に照らし合わせて調整し最後に結合して戻り値とする方針で処理している。この方針により、使ってはいけない文字列の削除や親ディレクトリにさかのぼる処理を分かりやすいコードで実装することができる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?