美文网首页
[24]Unix路径简化-搜狐2018秋

[24]Unix路径简化-搜狐2018秋

作者: jdzhangxin | 来源:发表于2018-10-27 17:26 被阅读20次

    1.题目描述

    简化 Unix 风格的路径,需要考虑的包括 /../, //, /./ 等情况

    • 输入描述:
      Unix 风格的路径
    • 输出描述:
      简化后的 Unix 风格路径
    • 输入示例:
      /a/./b/../../c/
      
    • 输出示例:
      /c
      

    2.题目解析

    Unix路径有如下规则

    1. 路径由文件名和文件描述符/构成。
    2. 多个连续的/当作为单个/
    3. .表示本级目录。
    4. ..表示返回上级目录。
    5. 最开始的/表示根目录,向上返回到根目录,不能再向上返回。

    根据上述规则解析文本。

    3.参考答案

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        string s;
        cin >> s;
        vector<string> dirs;
        for(int i = 0;i<s.size();++i){
            // 连续多个斜杠
            if(s[i] == '/') continue;
            // 处理.
            if(s[i] == '.'){
                if(s[i+1] == '/') {
                    ++i; // 忽略.
                    continue;
                }
                if(s[i+1] == '.'){//
                    i+=2; // 除去..
                    if(!dirs.empty()) dirs.pop_back();
                    continue;
                }
            }
            // 路径名
            string name;
            name.append(1,s[i]);
            while(s[++i] != '/'){
                name.append(1,s[i]);
            }
            dirs.push_back(name);
        }
        if(dirs.empty()){ // 如果路径名为空保留根路径
            printf("/\n");
            return 0;
        }
        for(int i=0;i<dirs.size();++i){
            cout << '/' << dirs[i];
        }
        printf("\n");
        return 0;
    }
    
    #include <iostream> 
    #include <string> 
    #include <stack> 
    using namespace std;
    
    int main(){ 
      string str; 
      cin >> str; 
      int len = str.length();
      
      // 存放文件夹
      stack<string> folders; 
    
      int i = 0; // 字符串起始位置
      while (i < len){ 
        string folder;// 文件夹名
    
        // 忽略多个连续的/
        while (i < len && str[i] == '/') i++; 
         
        // 拼装文件夹名
        while (i < len && str[i] != '/') { 
          folder += str[i]; 
          i++; 
        } 
        if (folder == "..") { // 返回上一级
          if (!folders.empty()) folders.pop(); 
        } else if (folder == "."){ // 跳过不处理
          continue; 
        } else if (!folder.empty()){ 
          folders.push(folder); 
        }
      } 
    
      // 如果为空,显示根目录
      if (folders.empty()){ 
        cout << "/"; 
        return 0; 
      } 
    
      // 连接目录
      string path = ""; 
      while (!folders.empty()) { 
        path = "/" + folders.top() + path;
        folders.pop(); 
      } 
      cout << path; 
      return 0;
    }
    

    牛客题目

    相关文章

      网友评论

          本文标题:[24]Unix路径简化-搜狐2018秋

          本文链接:https://www.haomeiwen.com/subject/majjoftx.html