LeetCode71 Simplify Path java题解
来源:互联网 发布:java excel报表工具 编辑:程序博客网 时间:2024/05/16 14:59
题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
解题思路:这题是简化目录,每一级目录前面都有一个斜杠,我可以首先对斜杠进行分割,分割之后得到的结果无外乎4种情况:正常目录名称,空字符,".",".."。对于“.”和空字符我们忽略它,对于正常的目录名称我们直接压入栈,对于"..",我们把栈顶元素出栈。通过这些处理之后,如果栈为空我们就返回根目录,如果栈不为空我们就逐个出栈并在每个元素前面加一个斜杠,最先出的位于路径的最后面。
代码:
import java.sql.Array;import java.util.Stack;public class LeetCode71_SimplifyPath {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubString input="/a/./b/../../c/";System.out.println(simplifyPath(input));}public static String simplifyPath(String path) {String[] pathArray=path.split("/");int length=pathArray.length;Stack< String> stack=new Stack<>();String result="";for(int i=0;i<length;i++){if(pathArray[i].equals("")||pathArray[i].equals(".")){}else if(pathArray[i].equals("..")){if(!stack.isEmpty()){stack.pop();}}else {stack.push(pathArray[i]);}}if(stack.isEmpty())return "/";while(!stack.isEmpty()){result="/"+stack.pop()+result;}return result; }}
0 0
- LeetCode71 Simplify Path java题解
- Simplify Path Leetcode71
- LeetCode71. Simplify Path
- Leetcode71: Simplify Path
- leetcode71. Simplify Path
- LeetCode71 Simplify Path
- LeetCode71——Simplify Path
- 算法设计与分析HW8:LeetCode71.Simplify Path
- LeetCode题解:Simplify Path
- leetcode题解-71. Simplify Path
- [Leetcode] Simplify Path (Java)
- Simplify Path (Java)
- [LeetCode][Java] Simplify Path
- LeetCode|Simplify Path-java
- Simplify Path leetcode java
- LeetCode 题解(16): Simplify Path
- (Java)LeetCode-71. Simplify Path
- 【leetcode】71. Simplify Path【java】
- 播放器大测评
- linux 设置环境变量的方法
- [USACO Jan09]安全路径Safe Travel解题报告
- Longest Consecutive Sequence
- 【剑指Offer学习】【面试题25:二叉树中和为某一值的路径】
- LeetCode71 Simplify Path java题解
- objc写一个NSMutableArray不连续索引替换对象的方法
- 微信java开发(nat123配制本地环境)
- 【Oracle】ORA-00257归档日志写满的解决方法
- oracle session和process的关系
- [C++ primer]第六章笔记-函数
- java实习日记一
- cs193p assignment4 遇到问题及解决过程2
- [Mac] Mac OS/iOS/XCode版本历史