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

    Description

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

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

    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".

    思路

    • 实现一个函数,每一次返回一个文件夹或文件名
    • 若是"..",则保存路径的vector从末尾删除一个,代表跳到上一级目录
    • 若是".","/","" 则什么都不做
    • 若是正常文件名,则存入vector

    代码

    class Solution {
    public:
     string simplifyPath(string path) {
    		vector<string> res;
    		int len = path.size();
    		if (len == 0) return path;
    
    		int i = 0;
    		while (i < len){
    			string tmp = getNext(path, i, len);
    			if (tmp == ".."){
    				if (!res.empty()) res.pop_back();
    			}
    			else if (tmp == "." || tmp == "" || tmp == "/");
    			else res.push_back(tmp);
    		}
    
    
    		int s = res.size();
    		string str;
    		for (i = 0; i < s; ++i){
    			str += "/" + res[i];
    		}
    		return str == "" ? "/" : str;
    	}
    
    	string getNext(string& path, int &i, int len){
    		string res;
    		bool end = false;
    		while (i < len){
    			if (path[i] != '/')
    				res += path[i++];
    			else{
    
    				if (end){
    					break;
    				}
    				if (i + 1 < len && path[i + 1] == '/')
    				{
    					while (i + 1 < len && path[i + 1] == '/')
    						i++;
    				}
    				i++;
    				end = true;
    			}
    		}
    		return res;
    
    	}
    };
    
  • 相关阅读:
    9.17考试
    Something
    tesuto-Mobius
    7.22考试
    填坑...P1546 最短网络 Agri-Net
    P1125 笨小猴
    P2822 组合数问题
    致我们曾经刷过的水题
    Luogu P1186 玛丽卡
    Luogu P1726 上白泽慧音
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6920822.html
Copyright © 2011-2022 走看看