zoukankan      html  css  js  c++  java
  • [leetcode] 题型整理之字符串处理

    71. Simplify Path

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

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

    Corner Cases:

      • Did you consider the case where path = "/../"?
        In this case, you should return "/".
      • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
        In this case, you should ignore redundant slashes and return "/home/foo".

    java的split函数,只要separator的前“或者”后没有“别的”字符串就会返回一个空。

    linux系统当中,多余两个的点会被当作普通路径处理。

    public class Solution {
        public String simplifyPath(String path) {
            if (path.length() == 0) {
                return "";
            }
            String[] strs = path.split("/");
            StringBuilder result = new StringBuilder();
            LinkedList<String> stack = new LinkedList<String>();
            for (String string : strs) {
                switch (string) {
                    case "": stack.offer("/"); break;
                    case ".": break;
                    case "..": while (!stack.isEmpty() && stack.removeLast().equals("/")); break;
                    default: stack.offer(string);
                }
            }
            if (path.charAt(0) == '/') {
                result.append('/');
            }
            while (!stack.isEmpty()) {
                String string = stack.removeFirst();
                if (!string.equals("/")) {
                    result.append(string);
                    result.append('/');
                }
            }
            int ll = result.length();
            if (ll > 1 && result.charAt(ll - 1) == '/') {
                result.deleteCharAt(ll - 1);
            }
            return result.toString();
        }
    }
  • 相关阅读:
    iOS UI调试神器,插件injection for Xcode使用方法
    iOS 开发笔记-Objective-C之KVC、KVO
    iOS 测试企业应用的分发
    iOS 阅读唐巧博客心得
    iOS 添加启动图片
    Xcode 常用命令
    iOS 开发笔记
    iOS 开发常用链接总结
    iOS
    iOS UI基础
  • 原文地址:https://www.cnblogs.com/Gryffin/p/6231502.html
Copyright © 2011-2022 走看看