首页 > 代码库 > Simplify Path
Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
算法:根据/把path分割,再逐个判断
public class Solution { public String simplifyPath(String path) { String[] strs = path.split("/"); Stack<String> s = new Stack<String>(); for(int i=0;i<strs.length;i++){ if(strs[i].equals(".")){ }else if(strs[i].equals("..")){ if(!s.isEmpty()) s.pop(); }else if(strs[i].length()>0){ s.push(strs[i]); } } StringBuilder sb = new StringBuilder(); Iterator<String> it = s.iterator(); while(it.hasNext()){ String t = it.next(); sb.append("/").append(t); } String r=sb.toString(); if(r.length()==0) r+="/"; return r; } }
Simplify Path
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。