• Simplify Path


    题目:

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

    代码实现(未优化):

    #include <iostream>
    #include <stack>
    #include <string>
    using namespace std;
    class Solution {
    public:
        string simplifyPath(string path) {
    		return SplitString(path,"/");
        }
    	string SplitString(const string& s, const string& c)
    	{
    		stack<string>st;
    		int pos2 = s.find(c);
    		int pos1 = 0;
    		while(string::npos != pos2)
    		{
    			string te = s.substr(pos1, pos2-pos1);
    			
    			if(te.length() > 0){
    				
    				if(te.compare("..") == 0){
    					if(!st.empty())
    						st.pop();
    				}else if(te.compare(".") == 0){}
    				else{
    					st.push(te);
    				}
    			}
    			pos1 = pos2 + c.size();
    			pos2 = s.find(c, pos1);
    		}
    		if(pos1 != s.length()){
    			string te = s.substr(pos1);
    			if(te.compare("..") == 0){
    				if(!st.empty())
    					st.pop();
    			}else if(te.compare(".") == 0){}
    			else{
    				st.push(te);
    			}
    		}
    		string r = "";
    		while(st.empty() == NULL){
    			r =  "/" + st.top() + r ;
    			st.pop();
    		}
    		if(r.compare("") == 0){
    			r = "/";
    		}
    		return r;
    	}
    };
    int main(){
    	Solution s = Solution();
    	string r = s.simplifyPath("///");
    	cout << r << endl;
    }
    

      

  • 相关阅读:
    android data binding jetpack I 环境配置 model-view 简单绑定
    java 直接内存
    Android内存管理机制
    使用老版本的java api提交hadoop作业
    通过java api提交自定义hadoop 作业
    hadoop错误总结
    linux下eclipse闪退和重装jdk的方法
    完全分布式安装hadoop
    hadoop伪分布式安装
    2014年度总结
  • 原文地址:https://www.cnblogs.com/zhutianpeng/p/4263414.html
Copyright © 2020-2023  润新知