• 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;
    }
    

      

  • 相关阅读:
    React性能优化记录(不定期更新)
    JSX设置CSS样式详解
    org.tinygroup.htmlparser-Html解析器
    org.tinygroup.application-应用启动框架
    org.tinygroup.beancontainer-IOC、AOP框架
    org.tinygroup.vfs-虚拟文件系统
    org.tinygroup.templateengine-模板引擎
    org.tinygroup.dbfilter
    org.tinygroup.templateweb-模板文件处理器
    org.tinygroup.flow-流程引擎
  • 原文地址:https://www.cnblogs.com/zhutianpeng/p/4263414.html
Copyright © 2020-2023  润新知