力扣——简化路径

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

相关推荐
CoovallyAIHub9 分钟前
MSD-DETR:面向机车弹簧检测的可变形注意力Detection Transformer
算法·架构
CoovallyAIHub13 分钟前
不改权重、不用训练!BEM用背景记忆抑制固定摄像头误检,YOLO/RT-DETR全系有效
算法·架构·github
Struggle_975518 分钟前
算法知识-从递归入手三维动态规划
算法·动态规划
yuan1999724 分钟前
使用模糊逻辑算法进行路径规划(MATLAB实现)
开发语言·算法·matlab
不才小强27 分钟前
线性表详解:顺序与链式存储
数据结构·算法
CoovallyAIHub27 分钟前
上交+阿里 | Interactive ASR:Agent框架做语音识别交互纠错,1轮交互语义错误率降57%
算法·架构·github
Aaron158838 分钟前
8通道测向系统演示科研套件
人工智能·算法·fpga开发·硬件工程·信息与通信·信号处理·基带工程
计算机安禾43 分钟前
【数据结构与算法】第42篇:并查集(Disjoint Set Union)
c语言·数据结构·c++·算法·链表·排序算法·深度优先
吃着火锅x唱着歌1 小时前
LeetCode 150.逆波兰表达式求值
linux·算法·leetcode
YuanDaima20481 小时前
二分查找基础原理与题目说明
开发语言·数据结构·人工智能·笔记·python·算法