首页 > > > [LeetCode] Simplify Path
Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".
解题思路:
化简路径。可以用一个栈来记录。遍历原路径,遇到/,则判断最近一个单词。若为"."则什么也不做。若"..",弹出栈顶元素,否则入栈。
有一个比较巧的办法是,直接在path后面添加一个斜杠,这样就能避免讨论后面有斜杠还是没有斜杠了。
class Solution {
public:
string simplifyPath(string path) {
stack ss;
path = path + "/";
int len = path.length();
string s="";
for(int i=0; i
转载请注明: » [LeetCode] Simplify Path
<!--
-->
原文作者:;如有侵权,请联系管理员删除。