2022.01.06 - 200.简化路径

文章目录

1. 题目

2022.01.06 - 200.简化路径
2022.01.06 - 200.简化路径

2. 思路

(1) 栈+双指针法

  • 遍历路径,利用栈和双指针法模拟即可。

3. 代码

import java.util.LinkedList;

public class Test {
    public static void main(String[] args) {
    }
}

class Solution {
    public String simplifyPath(String path) {
        int n = path.length();
        LinkedList<String> list = new LinkedList<>();
        int left = 0;
        int right = 0;
        while (left < n) {
            while (left < n && path.charAt(left) == '/') {
                left++;
            }
            if (left < n) {
                right = left;
                while (right < n && path.charAt(right) != '/') {
                    right++;
                }
                String s = path.substring(left, right);
                if (s.equals("..")) {
                    if (list.size() > 0) {
                        list.pollLast();
                    }
                } else if (!s.equals(".")) {
                    list.offerLast(s);
                }
                left = right;
            }
        }
        if (list.isEmpty()) {
            return "/";
        }
        StringBuilder sb = new StringBuilder();
        while (!list.isEmpty()) {
            sb.append('/');
            sb.append(list.pollFirst());
        }
        return sb.toString();
    }
}
上一篇:webRTC中语音降噪模块ANS细节详解(三)


下一篇:深入理解c语言指针与内存