您的位置:首页 > 其它

LeetCode Simplify Path

2015-06-30 00:25 267 查看
Description:

Given an absolute path for a file (Unix-style), simplify it.

Solution:

用scanner和stack处理即可,用"/"作为分割器,然后每次遇到".."就出栈。最后将stack倒序输出即可。

import java.util.*;

public class Solution {
public String simplifyPath(String path) {
Scanner scan = new Scanner(path);
scan.useDelimiter("/");

String temp;
Stack<String> stack = new Stack<>();
while (scan.hasNext()) {
temp = scan.next();
if (temp.equals("..")) {
if (!stack.isEmpty())
stack.pop();
} else if (temp.equals(".")) {

} else if (temp.equals("")) {

} else {
stack.add(temp);
}
}

String ans = "";
while (!stack.isEmpty()) {
temp = stack.pop();
if (temp.equals(" "))
break;
ans = "/" + temp + ans;
}
if (ans.equals(""))
ans = "/";

// System.out.println(ans);
return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: