[LintCode] Simplify Path

主要须要解决的问题是字符串分割。直接的做法是定位/之间的字符串或者自己编写split函数,并根据要求解析。简洁的做法是使用stringstream做字符串分割。

写法1:直接双指针循环定位

string simplifyPath(string &path) {
    if (path.empty()) return path;
    
    vector<string> vec;
    int start = 0, end = 1, n = path.size();
    while (end < n) {
        while (end < n && path[end] != '/') end++;
        string str = path.substr(start, end - start);
        if (str == "/" || str == "/.") ; // do nothing
        else if (str == "/..") {
            if (!vec.empty()) vec.pop_back();
        } else {
            vec.push_back(str);
        }
        start = end; end++;
    }
    
    if (vec.empty()) return "/";
    
    string ret;
    for (auto& str : vec) {
        ret += str;
    }
    return ret;
}

写法2:使用stringstream分割字符串

string simplifyPath(string& path) {
    if (path.empty()) return path;

    vector<string> vec;
    stringstream ss(path);
    string str;
    while (getline(ss, str, '/')) {
        if (str.empty() || str == ".") {
            continue;
        } else if (str == "..") {
            if (!vec.empty()) vec.pop_back();
        } else {
            vec.push_back(str);
        }
    }

    if (vec.empty()) return "/";

    string ret;
    for (auto& str : vec) {
        ret += ("/" + str);
    }
    return ret;
}
posted @ 2017-09-11 22:07  mioopoi  阅读(171)  评论(0编辑  收藏  举报