LeetCode-Add to List 71. Simplify Path

来源:互联网 发布:网络应用层协议有哪些 编辑:程序博客网 时间:2024/06/09 22:31

问题描述

  1. 给定一个Unix绝对路径,简化该路径并返回。
  2. 例如:path = “/home/”, => “/home”
    path = “/a/./b/../../c/”, => “/c”

解题思路

利用栈来求解,从最左边开始依次取出两个/ /之间的字符串,如果该字符串是“..”,则在栈中弹出一个路径字符串;如果该字符串是“.”或者“”,栈保持不变;否则,将字符串压栈。然后再全部弹出组成新的路径。

代码

import java.util.Stack;public class Solution {    public String simplifyPath(String path) {        if(path==null || path.length()==0)            return "";        Stack<String> stack=new Stack<String>();        int first=path.indexOf("/");        int second=0;        while(path.length()>0){            second=path.indexOf("/",first+1);            if(second==-1)                second=path.length();            String tem=path.substring(first+1,second);            path=path.substring(second,path.length());            if(tem.equals("..")){//比较两个字符串是否相等一定是equals而不是==!!                if(!stack.empty())                    stack.pop();            }else if(tem.equals(".") || tem.equals(""))                continue;            else{                stack.push("/"+tem);            }            first=0;        }        String result="";        if(stack.empty())            return "/";        while(!stack.empty())            result=stack.pop()+result;        return result;    }}

因为是函数的输入是绝对路径,因此字符串必然是从“/”开始,因此可以让first变量恒为0.如下所示:

import java.util.Stack;public class Solution {    public String simplifyPath(String path) {        if(path==null || path.length()==0)            return "";        Stack<String> stack=new Stack<String>();        //int first=path.indexOf("/");        int second=0;        while(path.length()>0){            second=path.indexOf("/",0+1);            if(second==-1)                second=path.length();            String tem=path.substring(0+1,second);            path=path.substring(second,path.length());            if(tem.equals("..")){                if(!stack.empty())                    stack.pop();            }else if(tem.equals(".") || tem.equals(""))                continue;            else{                stack.push("/"+tem);            }            //first=0;        }        String result="";        if(stack.empty())            return "/";        while(!stack.empty())            result=stack.pop()+result;        return result;    }}
原创粉丝点击