leetcode-Simplify Path

本文介绍了一种简化Unix风格文件路径的方法,通过使用C++中的vector来模拟栈操作,实现了对路径中'.'和'..'的有效处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

思路:字符串的处理,依然考虑双指针,

       用vector实现栈的功能:

       遇到.不变;

       遇到..如果vector不为空,则弹出最后一个,

       其他,压入vecort;

代码:

string simplifyPath(string path) {
       vector<string> tempVector;
string res;
int len=path.length();
int i=0;
string temp="";
int start=0;
int end=0;
while(start < len)
{
end=start;
while(end<len && path[end]!='/')
{
end++;
}
temp=path.substr(start,end-start);
if(temp==".."&&!tempVector.empty())
tempVector.pop_back();
else if(temp!="" && temp!="."&&temp!="..")
tempVector.push_back(temp);
start=end+1;


}
if(tempVector.size() == 0)
{
res="/";
return res;
}
int j=0;
int count=tempVector.size();
while(j<count)
{
res=res+"/";
res=res+tempVector[j];
++j;
}

return res;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值