问题:
给出一组全路径文件数组,删除子目录。
Example 1: Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"] Output: ["/a","/c/d","/c/f"] Explanation: Folders "/a/b/" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem. Example 2: Input: folder = ["/a","/a/b/c","/a/b/d"] Output: ["/a"] Explanation: Folders "/a/b/c" and "/a/b/d/" will be removed because they are subfolders of "/a". Example 3: Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"] Output: ["/a/b/c","/a/b/ca","/a/b/d"] Constraints: 1 <= folder.length <= 4 * 10^4 2 <= folder[i].length <= 100 folder[i] contains only lowercase letters and '/' folder[i] always starts with character '/' Each folder name is unique.
解法:
先对数组排序,得到的顺序则为:
父目录,在子目录前,
从头往后遍历,先加入结果的目录,一定为后加入的父目录,或者两者没有父子关系。
那么只有当前最后加入结果的目录,有可能为下一个遍历目录的父目录,
因此只用判断res.back()是否为当前遍历值的父目录即可。
这里的判断方法为:
当前遍历值.substr()==res.back()+"/" ??
若是,则不需要加当前遍历值入res,否则,加入。
代码参考:
1 class Solution { 2 public: 3 vector<string> removeSubfolders(vector<string>& folder) { 4 vector<string> res; 5 sort(folder.begin(), folder.end()); 6 for(string cur:folder){ 7 if(!res.empty()){ 8 string tmp=res.back()+"/"; 9 int len=tmp.size(); 10 if(cur.substr(0,len)==tmp) continue; 11 } 12 res.push_back(cur); 13 } 14 return res; 15 } 16 };