题解 | #牛群的危险路径#
牛群的危险路径
https://www.nowcoder.com/practice/c3326fb3ac0c4a658305483482943074
知识点
字符串,队列
解题思路
队列的应用,通过“/”分割字符串形成split数组。
遍历这个数组,如果是空的或者字符串是“."那么什么都不用操作。
如果是".."那么就需要让队列中队首元素出队,如果是其他字符串则入队。
最后将队列中的全部元素取出放进字符串中。
注意如果队列中没有任何元素则返回“/”。
Java题解
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param path string字符串 * @return string字符串 */ public String find_dangerous_cow_path (String path) { // write code here String[] split = path.split("/"); Deque<String> deque = new ArrayDeque<>(); for (String s : split) { if(s.isEmpty() || s.equals(".")) continue; if(s.equals("..")){ deque.pollFirst(); } else{ deque.offerFirst(s); } } StringBuilder ans = new StringBuilder(); while(!deque.isEmpty()){ ans.append("/"); ans.append(deque.pollLast()); } if(ans.length() == 0) return "/"; return ans.toString(); } }