首页 > 代码库 > LeetCode-Simplify Path
LeetCode-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.
Solution:
1 public class Solution { 2 public String simplifyPath(String path) { 3 if (path.isEmpty()) return ""; 4 5 StringBuilder builder = new StringBuilder(); 6 builder.append(‘/‘); 7 int index = 1; 8 while (index<path.length()){ 9 //get the next directory command.10 int next = index;11 while (next<path.length() && path.charAt(next)!=‘/‘) next++;12 String dir = path.substring(index,next);13 if (dir.equals(".") || dir.isEmpty()){14 index = next+1;15 continue;16 } else if (dir.equals("..")){17 pathBack(builder);18 } else {19 builder.append(dir);20 builder.append(‘/‘);21 }22 index = next+1;23 }24 25 if (builder.length()>1 && builder.charAt(builder.length()-1)==‘/‘)26 builder.deleteCharAt(builder.length()-1);27 return builder.toString();28 }29 30 public void pathBack(StringBuilder builder){31 builder.deleteCharAt(builder.length()-1);32 while (builder.length()>0 && builder.charAt(builder.length()-1)!=‘/‘)33 builder.deleteCharAt(builder.length()-1);34 if (builder.length()==0) builder.append(‘/‘);35 }36 }
LeetCode-Simplify Path
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。