第25题 Simplify Path

来源:互联网 发布:mac如何下载魔兽世界 编辑:程序博客网 时间:2024/06/17 05:06

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
原创粉丝点击