zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    团队项目——需求规格说明书
    UML
    第二次团队作业——预则立&&他山之石
    团队选题报告
    团队展示
    ubuntu下使用pyinstaller将python文件打包成exe(py文件中含有keras框架的代码)
    ubuntu 为项目配置虚拟环境
    安装cuda9.0 + cudnn7.0 与 cuda8.0共存
    ubuntu 16.04 + cuda8.0 + cudnn 6.1 + tensorflow 1.4.0
    修改vs2013中MFC项目名称
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4015643.html
Copyright © 2011-2022 走看看