当前浏览器不支持播放音乐或语音,请在微信或其他浏览器中播放
Everything at Once Lenka - Two (Bonus Track Version)
题目描述
给一个Unix风格的绝对路径,简化他。注意的是绝对路径以/开始(root 目录),( . )代表当前的目录,( .. )代表父目录。
例如:
"/a/./" --> 表示停留在当前 'a'
"/a/b/.." --> 表示跳转到父目录,from 'b' to 'a'
"////" --> 连续多个 '/' 是有效的路径,等于单个'/'
Input : /home/
Output : /home
Input : /a/./b/../../c/
Output : /c
Input : /a/..
Output : /
Input : /a/../
Ouput : /
Input : /../../../../../a
Ouput : /a
Input : /a/./b/./c/./d/
Ouput : /a/b/c/d
Input : /a/../.././../../.
Ouput : /
Input : /a//b//c//////d
Ouput : /a/b/c/d
注意:大家可以在自己的终端试试,就很容易理解这道题意了。
灵感示意图
第一步 先把字符串拆分成数组根据( / )第二步
把目录元素入栈
第三步
把原始栈reverse,最后把reverse的栈元素一一出栈并拼接
主要代码
- (NSString *)simplifyPath:(NSString *)inputStr
{
NSMutableString *dirStr = [@"" mutableCopy];
//1
[dirStr appendString:@"/"];
//2
NSMutableArray *dirArray = [[inputStr componentsSeparatedByString:@"/"] mutableCopy];
//3
DSStack *newStack = [[DSStack alloc] initWithSize:20];
for (int i = 0 ; i < dirArray.count; i++)
{
//4
while ([dirArray[i] isEqualToString:@""])
{
i++;
}
//5
while (i < dirArray.count && ![dirArray[i] isEqualToString:@""])
{
if ([dirArray[i] isEqualToString:@"."])
{
}
else if ([dirArray[i] isEqualToString:@".."])
{
if (![newStack isEmpty]) {
[newStack popLastObject];
}
}
else
{
[newStack push:dirArray[i]];
}
i++;
}
}
//6
DSStack *newStack1 = [[DSStack alloc] initWithSize:20];
while (![newStack isEmpty])
{
[newStack1 push:[newStack popLastObject]];
}
//7
while (![newStack1 isEmpty])
{
if ([newStack1 sizeOfStack]!= 1)
{
[dirStr appendFormat:@"%@/",[newStack1 popLastObject]];
}
else
{
[dirStr appendFormat:@"%@",[newStack1 popLastObject]];
}
}
return dirStr;
}
思路描述
-
根路径是必须有一个( / )
-
根据( / )拆分字符串,目的为了后面把多个( / )变成单个( / )
-
创建一个栈结构
-
循环遍历数组如果元素是空字符串,index向后移动
-
把非空的元素目录比如a,b入栈。当碰到( . )不做操作,如果遇到( .. )如果栈不为空则出栈
-
创建一个辅助栈,reverse刚开始的那个栈,便于拼接字符串
-
拼接栈内的元素,但第一个不需要后缀( / )
GitHubDemo地址
GitHubDemo链接 [1] ---> 也可以在文章末尾点击 👉阅读原文 进入
References
[1] GithubDemo: https://github.com/renmoqiqi/100-Days-Of-iOS-DataStructure-Algorithm/tree/master/Day06
关注公众号最新动态