题解 | #牛群的危险路径#

牛群的危险路径

https://www.nowcoder.com/practice/c3326fb3ac0c4a658305483482943074

知识点:栈 字符串

思路:常规模拟题,使用分割字符spilt将其字符串分割开,然后对. 和..进行判断,进行模拟,最后识别入字符串返回结果即可

编程语言:java

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param path string字符串
     * @return string字符串
     */
    public String find_dangerous_cow_path(String path) {
        Stack<String> stk = new Stack<>();
        for (String x : path.split("/")) {
            if (x.isEmpty()) continue;
            if (x.equals(".")) {
                continue;
            }
            if (x.equals("..")) {
                if (!stk.isEmpty()) stk.pop();
                continue;
            }
            stk.push(x);
        }
        StringBuilder sb = new StringBuilder("/");
        for (String s : stk) {
            sb.append(s).append("/");
        }
        if (sb.length() > 1) {
            sb.setLength(sb.length() - 1);
        }
        return sb.toString();
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务