力扣——简化路径

https://leetcode.cn/problems/simplify-path/description/?envType=study-plan-v2\&envId=top-interview-150

思路:将串以/分割,判断字符串是..././其他,进行入栈和出栈,最后留下的就是结果,拼装一下就好了。

三个要点:

第一:字符串的比较统一拿equals来比

第二:队列的遍历一定要拿while,不要用for,除非一开始就拿个变量存下来长度,不然遍历时候长度在变化

第三:split()函数会让空开的地方分割出来空字符串""

举个栗子:

java 复制代码
String s = " a b  c";
String[] x = s.split(" ");
for(String unit:x)
	System.out.println(unit);

结果是

shell 复制代码
a
b

c

代码:

java 复制代码
class Solution {
    public String simplifyPath(String path) {
        String[] units = path.split("/");
        String ans="";
        Deque<String> queue = new LinkedList<>();
        for(int i=0;i<units.length;i++){
            //System.out.println(units[i]);
            if(units[i].equals("")||units[i].equals(".")) 
                continue;
            else if(units[i].equals("..")&&queue.size()>0)
                queue.removeFirst();
            else if(units[i].equals("..")&&queue.size()==0) 
                continue;
            else
                queue.addFirst(units[i]);  
        }
        //千万别这么写
        // for(int i=0;i<queue.size();i++){
        //     if(i>=1)ans+="/";
        //     ans+=queue.peekFirst();
        //     queue.removeFirst();
        // }
        List<String> list = new ArrayList<>();
        while(queue.size()!=0){
            list.add(queue.peekFirst());
            queue.removeFirst();
        }
        for(int i=list.size()-1;i>=0;i--){
            ans=ans+"/"+list.get(i);
        }
        if(ans.equals("")) 
            ans = "/";
        return ans;
    }
}

PS:LinkedList的API

相关推荐
phltxy12 小时前
C语言操作符详解
java·c语言·算法
aqiu11111112 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye13 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考13 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
玖玥拾14 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研15 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
a1879272183116 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_9622974816 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
辰烨chenye16 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展