71. 简化路径
实现方法,用栈
方法2,使用字符串
用python语言的实现,很多情况被忽略,这样可读性就差了点
class Solution { public String simplifyPath(String path) { Deque方法二:栈deque = new linkedList<>(); String[] strings = path.split("/"); for (String s : strings) { if(s.equals("..")){ if(!deque.isEmpty()) deque.removeLast(); else continue; } else if(s.equals(".") || s.equals("")) continue; else deque.addLast(s); } StringBuilder stringBuilder = new StringBuilder("/"); int size = deque.size(); for (int i = 0; i < size; i++) { stringBuilder.append(deque.removeFirst()); if(i < size - 1)stringBuilder.append('/'); } return stringBuilder.toString(); } } 作者:LittleSongFly 链接:https://leetcode-cn.com/problems/simplify-path/solution/zi-fu-chuan-leetcode-mei-ri-yi-ti-71-jia-dl38/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution { public String simplifyPath(String path) { String[] names = path.split("/"); Dequestack = new ArrayDeque (); for (String name : names) { if ("..".equals(name)) { if (!stack.isEmpty()) { stack.pollLast(); } } else if (name.length() > 0 && !".".equals(name)) { stack.offerLast(name); } } StringBuffer ans = new StringBuffer(); if (stack.isEmpty()) { ans.append('/'); } else { while (!stack.isEmpty()) { ans.append('/'); ans.append(stack.pollFirst()); } } return ans.toString(); } } 作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/simplify-path/solution/jian-hua-lu-jing-by-leetcode-solution-aucq/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
参考链接:
字符串实现
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)