LeetCode - Simplify Path

Simplify Path

2013.12.22 04:19

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

click to show corner cases.

Corner Cases:
  • Did you consider the case where path = "/../"?
    In this case, you should return "/".
  • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".

Solution:

  "." means current folder, ".." means parent folder, "/" or many consecutive "/"s mean directory separator.

  The input data can be very messy, so I decided to parse the folder names and output the result in neat format.

  Split the full path by "/" to get the items.

  Process description:

    1. When encountered a folder name, push it into the vector.

    2. When encountered a ".", ignore it.

    3. When encountered a "..", pop an item from the vector.

    4. Concatenate the items in the vector together with "/" to form a full path and return it.

  Time complexity is O(n), space complexity is O(n), where n is the length of the path string.

Accepted code:

 1 // 2CE, 1AC

 2 #include <string>

 3 #include <vector>

 4 using namespace std;

 5 

 6 class Solution {

 7 public:

 8     string simplifyPath(string path) {

 9         // IMPORTANT: Please reset any member data you declared, as

10         // the same Solution instance will be reused for each test case.

11         vector<string> tokens;

12         string token;

13         

14         int i, j, n;

15         

16         tokens.clear();

17         n = path.length();

18         if(n <= 0){

19             return "/";

20         }

21         

22         i = 0;

23         while(i < n){

24             while(i < n && path[i] == '/'){

25                 ++i;

26             }

27             j = i + 1;

28             while(j < n && path[j] != '/'){

29                 ++j;

30             }

31             

32             if(i >= n){

33                 break;

34             }

35             token = path.substr(i, j - i);

36             if(token == ".."){

37                 if(tokens.size() > 0){

38                     tokens.pop_back();

39                 }

40             }else if(token != "."){

41                 // 2CE here, parameter missing, tokens.push_back();

42                 tokens.push_back(token);

43             }

44             

45             i = j;

46         }

47         

48         string res;

49         

50         if(tokens.size() <= 0){

51             return "/";

52         }else{

53             res = "";

54             for(i = 0; i < tokens.size(); ++i){

55                 res = res + "/" + tokens[i];

56             }

57             tokens.clear();

58             return res;

59         }

60     }

61 };

 

你可能感兴趣的:(LeetCode)