码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Simply Path

时间:2014-10-10 14:29:30      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   使用   ar   for   sp   div   

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

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

难度:85,虽然不难,但是里面关于LinkedList实现的栈的各种技巧的使用,还是有比较高要求的。

先用了String[] split (String  regex)这个函数。先把输入字符串以‘/‘为分隔符分来,如果遇到‘.‘或者空输入什么都不做。如果遇到‘..‘就弹栈。其他情况则将对应元素入栈。这样,栈里面存的就是最后简化的路径,我们只需把栈里面的元素按从末尾到栈顶的顺序取出来,之间添加“/”就可以了。

这里要取栈底元素,用的方法是:stack.removeLast();

还有就是写的时候,忽视了String是一个object, ‘==’表示内存地址都一样的情况,equals才是仅仅值相同的情况

split函数的用法:The string "boo:and:foo", for example, split(":")的结果是 {“boo”, "and", "foo"}; 需要注意的是:Trailing empty strings are not included in the resulting array.比如,split("o")的结果是{“b”, "", ":and:f"}

 1 public class Solution {
 2     public String simplifyPath(String path) {
 3         if (path==null || path.length()==0) {
 4             return "";
 5         }
 6         String res = "";
 7         String[] strs = path.split("/");
 8         LinkedList<String> stack = new LinkedList<String>();
 9         for (int i=0; i<strs.length; i++) {
10             if (strs[i].equals("")) continue;
11             if (strs[i].equals("..") && !stack.isEmpty()) {
12                 stack.pop();
13             }
14             else if (!strs[i].equals(".") && !strs[i].equals("..")) {
15                 stack.push(strs[i]);
16             }
17         }
18         if (stack.isEmpty()) return "/";
19         while (!stack.isEmpty()) {
20             String temp = stack.removeLast();
21             res = res + "/" + temp;
22         }
23         return res;
24     }
25 }

 

Leetcode: Simply Path

标签:style   blog   color   io   使用   ar   for   sp   div   

原文地址:http://www.cnblogs.com/EdwardLiu/p/4015643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!