• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Simplify Path

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"}

第二遍做法:(注意17行,顺序写出Stack里的元素)

 1 public class Solution {
 2     public String simplifyPath(String path) {
 3         if (path==null || path.length()==0) return "";
 4         Stack<String> st = new Stack<String>();
 5         String[] strs = path.split("/");
 6         for (int i=0; i<strs.length; i++) {
 7             String cur = strs[i];
 8             if (cur.equals("") || cur.equals(".")) continue;
 9             if (cur.equals("..")) {
10                 if (!st.isEmpty()) st.pop();
11             }
12             else {
13                 st.push(cur);
14             }
15         }
16         StringBuffer res = new StringBuffer();
17         for (String each : st) {
18             res.append("/");
19             res.append(each);
20         }
21         return res.length()==0? "/" : res.toString();
22     }
23 }

 

posted @ 2014-10-10 13:20  neverlandly  阅读(334)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3