zoukankan      html  css  js  c++  java
  • 71. Simplify Path

    Given an absolute path for a file (Unix-style), simplify it. 

    For example,
    path = "/home/", => "/home"
    path = "/a/./b/../../c/", => "/c"
    path = "/a/../../b/../c//.//", => "/c"
    path = "/a//b////c/d//././/..", => "/a/b/c"

    In a UNIX-style file system, a period ('.') refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki/Path_(computing)#Unix_style

    Corner Cases:

      • Did you consider the case where path = "/../"?
        In this case, you should return "/".
      • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
        In this case, you should ignore redundant slashes and return "/home/foo".

    AC code:

    class Solution {
    public:
        string simplifyPath(string path) {
            string res, tmp;
            vector<string> stk;
            stringstream ss(path);
            while(getline(ss,tmp,'/')) {
                if (tmp == "" or tmp == ".") continue;
                if (tmp == ".." and !stk.empty()) stk.pop_back();
                else if (tmp != "..") stk.push_back(tmp);
            }
            for(auto str : stk) res += "/"+str;
            return res.empty() ? "/" : res;
        }
    };
    
    Runtime: 4 ms, faster than 99.84% of C++ online submissions for Simplify Path.
    Get line from stream into string

    Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, ' ', for (2)).

    The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.

    If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).

    Note that any content in str before the call is replaced by the newly extracted sequence.

    Each extracted character is appended to the string as if its member push_back was called.

    Parameters

    is
    istream object from which characters are extracted.
    str
    string object where the extracted line is stored.
    The contents in the string before the call (if any) are discarded and replaced by the extracted line.

    2. string和stringstream用法总结

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    activeMQ
    @Autowired与@Resource的区别
    maven工程下get的URI中带中文名称乱码解决
    linux下安装jdk
    Redis集群之Jedis的使用
    格式化Json数据
    拷贝chrome控制台打印的对象
    为什么有的代码容易理解,有的难
    ant design pro总是跨域,proxy也没设置错误,原来是浏览器缓存,清理Chrome缓存就可以了
    VScode:保存格式化问题,ESLint插件和编辑器本身冲突
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9833262.html
Copyright © 2011-2022 走看看