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;
    
    	}
    };
    
  • 相关阅读:
    SpringMVC数据绑定
    SpringMVC概述
    应用Spring和Hibernate(C3P0数据池)写数据库交互项目
    Spring的AOP特性
    Sping框架的IOC特性
    MD5加密字符串
    重力感应 视频横竖屏切换
    自定义View(三)实现简单的可拖动、可缩放的ImageView
    自定义View(二)增加View的属性
    自定义View的学习(一) 自绘制控件
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6920822.html
Copyright © 2011-2022 走看看