题解 | #牛群的危险路径#
牛群的危险路径
https://www.nowcoder.com/practice/c3326fb3ac0c4a658305483482943074
所用语言
Java
所用知识
字符串、队列
解题思路
先用split把字符串分割
判断根据情况存入队列中
使用stringBuffer连接字符串
完整代码
public static String find_dangerous_cow_path(String path) {
// write code here
Deque<String> deque = new LinkedList<>();
String[] strs = path.split("/");
for (int i = 0; i < strs.length; i++) {
if(strs[i].isEmpty()||strs[i].equals(".")){
continue;
}else if(strs[i].equals("..")){
if(!deque.isEmpty()){
deque.pop();
}
}else {
deque.push(strs[i]);
}
}
StringBuilder stringBuilder = new StringBuilder();
while(!deque.isEmpty()){
System.out.println(deque.peekFirst());
stringBuilder.insert(0,"/"+deque.removeFirst());
}
return stringBuilder.equals("")?"/":stringBuilder.toString();
}
#牛群的危险路径#