https://leetcode.com/problems/simplify-path/
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.
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 not end with a trailing /
. Also, the canonical path must be the shortest string representing the absolute path.
Example 1:
Input: "/home/" Output: "/home" Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: "/../" Output: "/" Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: "/home//foo/" Output: "/home/foo" Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:
Input: "/a/./b/../../c/" Output: "/c"
Example 5:
Input: "/a/../../b/../c//.//" Output: "/c"
Example 6:
Input: "/a//bc/d//././/.." Output: "/a/b/c"
算法思路:
题目大意是,在给定的路径中,只存在三种特殊符号(/ . .. ),现在在路径中要直接去掉(.),对于(..),去掉去前面的一个字符串,多个(/)保留一个,且最后面不能有(/)。用一个向量vector<string>tmp保存路径中遇到的字符串。
- 首先使用while循环去掉前置(/),然后判断是否已经出界,出界表示这一段全是(/),直接退出;
- 找到下一个非(/)位置,那么[start,end]区间就是可能需要保存在字符串;
- 判断字符串等于(.)(..)(字母字符串)并执行相应操作;
- while循环是否结束?没结束回到第一条。
后续就是将保存在tmp中的字符串转换成res,前提tmp非空。
class Solution {
public:
string simplifyPath(string path) {
int n=path.size();
if(n==0) return "/";
vector<string> tmp;
int i=0;
while(i<n){
while(i<n && path[i]=='/') i++;
if(i==n) break;
int start=i;
while(i<n && path[i]!='/') i++;
int end=i-1;
string str=path.substr(start,end-start+1);
if(str==".") continue;
else if(str==".."){
if(!tmp.empty()) tmp.pop_back();
}else tmp.push_back(str);
}
if(tmp.empty()) return "/";
string res="";
for(auto s : tmp){
res+="/"+s;
}
return res;
}
};
参考资料: