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();
        }
    }
  • 相关阅读:
    Java日历表
    递归实现文件的大小计算
    将机器学习的个性化推荐与社会化机制相结合
    设计模式——抽象工厂模式
    从mysql到nosql
    设计模式——Adapter模式(变压器)
    Java 正则匹配
    对象集合转换为datatable
    sql1
    Oracle Index 相關知識
  • 原文地址:https://www.cnblogs.com/Gryffin/p/6231502.html
Copyright © 2011-2022 走看看