Leetcode—71.Simplify Path

Type:medium

Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.

In a UNIX-style file system, a period .refers to the current directory. Furthermore, a double period ..moves the directory up a level. For more information, see:Absolute path vs relative path in Linux/Unix

Note that the returned canonical path must always begin with a slash /, and there must be only a single slash /between two directory names. The last directory name (if it exists) must notend with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.


输出最简化路径,有以下几种考虑:

1、若遇到'/',只保留一个'/'

2、若遇到‘/../’,则回退一级目录

3、若遇到'/./',则忽略



string simplifyPath(string path) {

        int n = path.length();

        string ret;

        vector temp;

        int i = 0;

        while(i < n){

            while(path[i] == '/' && i < n) ++i;

            if(i == n) break;

            int start = i;

            while(path[i] != '/' && i < n) ++i;

            int end = i - 1;

            string s = path.substr(start, end - start + 1);

            if(s == ".."){

                if(!temp.empty()) temp.pop_back();

            }else if(s != "."){

                temp.push_back(s);

            }

        }

        if(temp.empty()) return "/";

        for(int m = 0; m

            ret += '/' + temp[m];

        }

        return ret;

    }

你可能感兴趣的:(Leetcode—71.Simplify Path)