题解 | #简化目录路径#
简化目录路径
http://www.nowcoder.com/practice/3177bcbfd947409ba833efb5a5b4a24c
简化目录路径:
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param path string字符串
* @return string字符串
*/
public String simplifyPath (String path) {
// write code here
Stack<String> stack=new Stack<>();
for(String i : path.split("/")){
if(i.equals("..")&&!stack.isEmpty()){
stack.pop();
}else if(!i.equals("..")&&!i.equals(".")&&!i.equals("")){
stack.push(i);
}
}
StringBuilder sb=new StringBuilder();
for(String i:stack){
sb.append("/");
sb.append(i);
}
return sb.length() == 0 ?"/":sb.toString();
}
}