zoukankan      html  css  js  c++  java
  • [leetcode]Simplify Path

    用了个数组来存路径。遇'.'跳过,遇'..'回退。看了一下别人的,和我的思路一样,只是人家用了stack。我用了原始的arraylist而已。

    参考里的答案用了String[] splits = path.trim().split("/"); 商业代码这么写肯定好,这里如果用i,j,更好练习面试而已。

    public class Solution {
        public String simplifyPath(String path) {
            // Start typing your Java solution below
            // DO NOT write main() function
            if (path == null || path.length() == 0) return "/";
            int len = path.length();
            ArrayList<String> array = new ArrayList<String>();
            int i = 0;
            int j = 0;
            while (i < len) {
                while (i < len && path.charAt(i) == '/') {
                    i++;
                }
                j = i;
                while (i < len && path.charAt(i) != '/') {
                    i++;
                }
                if (j != len) {
                    String tmp = "";
                    if (i == len) {
                        tmp = path.substring(j);
                    }
                    else {
                        tmp = path.substring(j, i);
                    }
                    if (tmp.equals(".")) {
                        // do nothing
                    }
                    else if (tmp.equals("..")) {
                        if (array.size() != 0) {
                            array.remove(array.size() - 1);
                        }
                    }
                    else {
                        array.add(tmp);
                    }
                }            
            }
            StringBuilder sb = new StringBuilder();
            for (int x = 0; x < array.size(); x++) {
                sb.append('/');
                sb.append(array.get(x));
            }
            String ret = sb.toString();
            if (ret.length() == 0) return "/";
            else return ret;
        }
    }
    

      

  • 相关阅读:
    第一阶段意见评论
    软件工程--第十一周学习进度
    第一阶段SCRUM冲刺 10
    冲刺(三)
    冲刺(二)
    冲刺(一)
    梦断代码阅读笔记01
    第八周总结
    NABCD项目分析
    第七周总结
  • 原文地址:https://www.cnblogs.com/lautsie/p/3251644.html
Copyright © 2011-2022 走看看