第25题 Simplify Path

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

For example,

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

click to show corner cases.

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

Solution in Java:

public class Solution {
    public String simplifyPath(String path) {
        String[] paths = path.split("/+");
        Stack<String> spath = new Stack<String>();
      
        for(int i=0; i<paths.length; i++){
            if(!paths[i].equals("")&&!paths[i].equals(".")) spath.push(paths[i]);
        }
       
        String simPath="";
        int back=0;
        while(!spath.empty()){
            String cur = spath.pop();
            if(cur.equals(".."))    back++;
            else if(back>0) back--;
            else{
                simPath= "/" + cur + simPath;
            }
        }
        if(simPath.equals("")) simPath="/";
        return simPath;
    }
}
Note: Java字符串比较要用equals()函数哦。String分割有函数split()。Java中Stack的pop()函数会返回栈顶对象并且将对象pop出来。

Solution in c++:

class Solution {
public:
    string simplifyPath(string path) {
        int length = path.length();
        int start=0, index=0;
        stack<string> paths;
        while(index<length){
            if(path[start]=='/')    {
                start++;
                index++;
            }
            else if(path[index]=='/'){
                string curPath = path.substr(start, index-start);
                if(!(curPath==".")){
                    paths.push(curPath);
                }
                start=index+1;
                index=start;  
            }
            else{
                index++;
            }
        }
        if(start!=length){
            string curPath = path.substr(start);
            if(!(curPath==".")) paths.push(curPath);
        }
        int back=0;
        string simPath="";
        while(!paths.empty()){
            string curPath=paths.top();
            paths.pop();
            if(curPath=="..")   back++;
            else if(back>0) back--;
            else  simPath= "/"+curPath +simPath;
        }
        if(simPath=="") simPath="/";
        return simPath;
    }
};

Note:C++的string没有split函数可用,需要自己实现。C++中字符串可以用"=="比较。C++中的stack类pop()函数return值为void,即只pop栈顶元素,不返回该对象的值。想要获取栈顶元素值,要先用top()元素获取元素值,再pop()。在java中与top()对等的函数是peak()。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值