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();
        }
    }
  • 相关阅读:
    MVC 导出CSV
    用Nero 10.0 刻录系统安装盘步骤
    还原Ghost系统步骤简单描述
    在XP系统中发布MVC3项目nopCommerce2.65及配置
    Win2003合并磁盘分区
    GridView常用操作及注意点
    SPGroup 和SPUser的常用操作
    【转】密封类
    Sharepoint 常用的Cmd 命令
    SharePoint 上传文件到图片库中代码
  • 原文地址:https://www.cnblogs.com/Gryffin/p/6231502.html
Copyright © 2011-2022 走看看