算法设计与分析HW8:LeetCode71.Simplify Path
来源:互联网 发布:4g网络哪家好 编辑:程序博客网 时间:2024/05/23 19:13
Description:
Given an absolute path for a file (Unix-style), simplify it.
Note:
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Solution:
Analysis and Thinking:
问题要求对输入的文件的绝对路径进行简化,并输出简化的路径结果。观察发现这是unix风格的文件路径命名,其重点是对字符串的处理,特别对“..”这一表示上级目录的符号的处理,本文利用了栈结构来处理,用栈来记录文件路径名,并对处理到的字符串是/或.或..或其他字符,做相应的处理。
Steps:
1.构建栈用于记录输入的文件路径名
2.遍历路径名,如果当前字符是'/',则不处理,跳至下一个字符
3.如果不是/,用一变量s存储字符子串,知道下一个'/'的出现
4.判断s是否为“..”,如果是,且当前路径栈不为空,则弹栈
5.如果s不为“”、“.”、".."三者之一,则将其入栈,如果文件路径还没遍历完,跳回2
6.将栈内元素弹出,并用一结果数组记录链接,返回结果数组
Codes:
class Solution { public: string simplifyPath(string path) { stack<string> pathRecoder; for(int i=0;i<path.size();) { while(path[i]=='/'&&i<path.size()) { i++; } string tempStr=""; while(path[i]!='/'&&i<path.size()) { tempStr=tempStr+path[i++]; } if(tempStr==".."&&tempStr.empty()) pathRecoder.pop(); else if(tempStr!=""&&tempStr!="."&&tempStr!="..") pathRecoder.push(tempStr); } string result=""; if(pathRecoder.empty()) { return"/"; } while(!pathRecoder.empty()) { result="/"+result+pathRecoder.top(); pathRecoder.pop(); } return result; } };
Results:
0 0
- 算法设计与分析HW8:LeetCode71.Simplify Path
- Simplify Path Leetcode71
- LeetCode71. Simplify Path
- Leetcode71: Simplify Path
- leetcode71. Simplify Path
- LeetCode71 Simplify Path
- 算法分析与设计课程(10):【leetcode】Simplify Path
- LeetCode71 Simplify Path java题解
- LeetCode71——Simplify Path
- [算法分析与设计] leetcode 每周一题: 071. Simplify Path
- LeetCode算法题目:Simplify Path
- (每日算法)Leetcode--Simplify Path (简单路径)
- 算法系列——Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- haut 1269: 爱看电视的LsF dfs
- redis持久化RDB和AOF
- 华为模拟器eNSP-各种奇葩故障解决办法
- CentOS6.5挂载 USB3.0(并且是NTFS格式的)
- 小知识:html标签中的javascript:
- 算法设计与分析HW8:LeetCode71.Simplify Path
- 文章标题
- MATLAB启动时打开多个窗口问题的解决
- 二分图匹配csu1887Cuckoo Hashing
- Java网络爬虫(七)--实现定时爬取与IP代理池
- 第九周:[Leetcode]494. Target Sum
- 让创新野蛮生长
- ECMAScript 6(8)——正则表达式的扩展
- mysql行列转换