力扣——简化路径

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

相关推荐
wljy113 小时前
牛客每日一题(2026.4.30) 整数域二分
c语言·c++·算法·蓝桥杯·二分
水蓝烟雨13 小时前
3335. 字符串转换后的长度 I
算法·leetcode
Dxy123931021613 小时前
HTML 如何使用 SVG 画曲线
前端·算法·html
westdata-Tm13 小时前
洛谷P1219 [USACO1.5] 八皇后 Checker Challenge
算法·深度优先·dfs
南宫萧幕13 小时前
MATLAB/Simulink 从零打通:HEV 能量管理 GA 联合仿真保姆级建模指南
开发语言·算法·matlab·汽车·控制·pid
小雅痞13 小时前
[Java][Leetcode middle] 15. 三数之和
java·算法·leetcode
图码13 小时前
矩阵数据结构入门指南:声明、初始化与基本操作
运维·数据结构·线性代数·算法·矩阵
Navigator_Z13 小时前
LeetCode //C - 1030. Matrix Cells in Distance Order
c语言·算法·leetcode
无敌昊哥战神13 小时前
【回溯算法巅峰之作】LeetCode 51. N皇后问题详解与常见避坑指南 (C/C++/Python)
c语言·算法·leetcode
mftang13 小时前
BSS段、Data段、Text段的具体含义和数据特性
数据库·算法