【leetcode】Simplify Path

来源:互联网 发布:变卡通人物声音软件 编辑:程序博客网 时间:2024/06/06 12:50

题目:将给定的路径名简化,返回最简形式。

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 slashstring strBetweenSlash;if(next_slash != path.npos){strBetweenSlash = path.substr(i, next_slash - i);}//not findelse{strBetweenSlash = path.substr(i, path_len - i);next_slash = path_len;}//back to parent dirif(strBetweenSlash.compare("/..") == 0){if(!simPath.empty())simPath.pop_back();else{i = next_slash;continue;}}//skipelse if(strBetweenSlash.compare("/") == 0){i = next_slash;continue;}//back to current dir,skipelse if(strBetweenSlash.compare("/.") != 0){simPath.push_back(strBetweenSlash);}i = next_slash;}if(simPath.empty())return "/";string re;//get the whole dirvector<string>::const_iterator cite = simPath.begin();while (cite != simPath.end()){re += *cite;++cite;}return re;}


1 0
原创粉丝点击