栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

71. 简化路径

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

71. 简化路径

目录

方法一:字符串方法二:栈

71. 简化路径


实现方法,用栈

方法2,使用字符串

用python语言的实现,很多情况被忽略,这样可读性就差了点

方法一:字符串
class Solution {
    public String simplifyPath(String path) {
        
        Deque deque = new linkedList<>();
        String[] strings = path.split("/");
        for (String s : strings) {
            if(s.equals("..")){
                if(!deque.isEmpty()) deque.removeLast();
                else continue;
            } else if(s.equals(".") || s.equals("")) continue;
            else deque.addLast(s);
        }
        StringBuilder stringBuilder = new StringBuilder("/");
        int size = deque.size();
        for (int i = 0; i < size; i++) {
            stringBuilder.append(deque.removeFirst());
            if(i < size - 1)stringBuilder.append('/');
        }
        return stringBuilder.toString();

    }
}

作者:LittleSongFly
链接:https://leetcode-cn.com/problems/simplify-path/solution/zi-fu-chuan-leetcode-mei-ri-yi-ti-71-jia-dl38/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
方法二:栈
class Solution {
    public String simplifyPath(String path) {
        String[] names = path.split("/");
        Deque stack = new ArrayDeque();
        for (String name : names) {
            if ("..".equals(name)) {
                if (!stack.isEmpty()) {
                    stack.pollLast();
                }
            } else if (name.length() > 0 && !".".equals(name)) {
                stack.offerLast(name);
            }
        }
        StringBuffer ans = new StringBuffer();
        if (stack.isEmpty()) {
            ans.append('/');
        } else {
            while (!stack.isEmpty()) {
                ans.append('/');
                ans.append(stack.pollFirst());
            }
        }
        return ans.toString();
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/simplify-path/solution/jian-hua-lu-jing-by-leetcode-solution-aucq/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

参考链接:
字符串实现

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/701450.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号