题目考察的知识点是:
字符串的遍历。
题目解答方法的文字分析:
先将相邻的"//"删掉一个;然后入栈,遇到"."出栈;然后栈中的元素就是最简路径,入string中,翻转字符串。
本题解析所用的编程语言:
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();
}
}

京公网安备 11010502036488号