首页 > 代码库 > 【leetcode】Simplify Path
【leetcode】Simplify Path
题目:将给定的路径名简化,返回最简形式。
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
虽然咋看起来比较杂乱,但还是比较整齐的,每个部分由‘/‘进行分割,就像文本处理中,由空格或tab分割的单词一样,对得到的不同的分割此进行不同的处理。得到的可能的分割词包括:
string simplifyPath(string path) { if(path.size() <= 1 || path[0] != '/') return path; vector<string> simPath; int path_len = path.size(); int i = 0; while (i < path_len) { int next_slash = path.find('/', i + 1); //find the next slash string strBetweenSlash; if(next_slash != path.npos) { strBetweenSlash = path.substr(i, next_slash - i); } //not find else{ strBetweenSlash = path.substr(i, path_len - i); next_slash = path_len; } //back to parent dir if(strBetweenSlash.compare("/..") == 0) { if(!simPath.empty()) simPath.pop_back(); else { i = next_slash; continue; } } //skip else if(strBetweenSlash.compare("/") == 0) { i = next_slash; continue; } //back to current dir,skip else if(strBetweenSlash.compare("/.") != 0) { simPath.push_back(strBetweenSlash); } i = next_slash; } if(simPath.empty()) return "/"; string re; //get the whole dir vector<string>::const_iterator cite = simPath.begin(); while (cite != simPath.end()) { re += *cite; ++cite; } return re; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。