力扣——简化路径

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

相关推荐
强盛小灵通专卖员43 分钟前
分类分割详细指标说明
人工智能·深度学习·算法·机器学习
IT猿手4 小时前
基于强化学习 Q-learning 算法求解城市场景下无人机三维路径规划研究,提供完整MATLAB代码
神经网络·算法·matlab·人机交互·无人机·强化学习·无人机三维路径规划
万能程序员-传康Kk7 小时前
旅游推荐数据分析可视化系统算法
算法·数据分析·旅游
PXM的算法星球8 小时前
【并发编程基石】CAS无锁算法详解:原理、实现与应用场景
算法
ll7788118 小时前
C++学习之路,从0到精通的征途:继承
开发语言·数据结构·c++·学习·算法
烨然若神人~8 小时前
算法第十七天|654. 最大二叉树、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树
算法
爱coding的橙子8 小时前
每日算法刷题Day2 5.10:leetcode数组1道题3种解法,用时40min
算法·leetcode
阳洞洞8 小时前
leetcode 18. 四数之和
leetcode·双指针
程序媛小盐9 小时前
贪心算法:最小生成树
算法·贪心算法·图论
Panesle9 小时前
分布式异步强化学习框架训练32B大模型:INTELLECT-2
人工智能·分布式·深度学习·算法·大模型