Simplify Path
来源:互联网 发布:联想笔记本网络开关 编辑:程序博客网 时间:2024/06/07 11:24
这是一道新知补课题,unix的文件path表示法:
当遇到“/../"则需要返回上级目录,需检查上级目录是否为空。
当遇到"/./"则表示是本级目录,无需做任何特殊操作。
当遇到"//"则表示是本级目录,无需做任何操作。
当遇到其他字符则表示是文件夹名,无需简化。
当字符串是空或者遇到”/../”,则需要返回一个"/"。
当遇见"/a//b",则需要简化为"/a/b"。
依题意,设计一个栈,做如下操作:
先将字符串依"/"分割出来,然后检查每个分割出来的字符串。
当字符串为空或者为".",不做任何操作。是并的逻辑关系好不好!!!!!
当字符串不为"..",则将字符串入栈。
当字符串为"..", 则弹栈(返回上级目录)。
path = "/home/", => "/home"path = "/a/./b/../../c/", => "/c"path = "/../", => "/"path = "/home//foo/", => "/home/foo"
public class Solution { public String simplifyPath(String path) {if (path == null) {return null;}String[] array = path.split("/");Stack<String> stack = new Stack<>();for (String str: array) {//if (!str.equals(".") || !str.equals("")) {if (!str.equals(".") && !str.equals("")) {if (str.equals("..")) {if (!stack.isEmpty()) {stack.pop();}} else {stack.push(str);}}}StringBuilder sb = new StringBuilder();while(!stack.isEmpty()) {sb.insert(0, stack.pop());sb.insert(0, "/");}return sb.length() == 0 ? "/" : sb.toString(); }}
0 0
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- python学习 stackflow社区 python的机器学习库
- 第4.3节 编写一个具有加、减、乘、除四则运算功能的计算机程序
- EasySwift/EasySwift 最简单,最高效,最时髦的swift开发全套解决方案
- UNITY3D圆形算法
- Android中的"架构"选择
- Simplify Path
- easyui的tab加载页面中的form重复提交
- Volley使用笔记(二)
- sar命令查看网卡流量
- Plus One
- Implement Queue using Stacks
- Power of Four
- 陶哲轩实分析-第14章 一致收敛
- 欢迎使用CSDN-markdown编辑器