LeetCode OJ:Simplify Path(简化路径)
2024-09-04 01:31:39
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
简化路径,linux下面简单的路径操作而已,代码如下:
class Solution {
public:
string simplifyPath(string path) {
stack<string> tokenStk;
int sz = path.size();
for (int i = ; i < sz; ++i){
if (path[i] == '/') continue;
else{
string tmp = "";
for (int j = i; j < sz && path[j] != '/'; ++j, ++i){
tmp.append(, path[i]);
}
if (tmp == ".."){
if (!tokenStk.empty())tokenStk.pop();
}
else if (tmp == ".")
continue;
else
tokenStk.push(tmp);
}
} vector<string> tokenVec;
while (!tokenStk.empty()){//存储的是反向的目录,将其输出打vector中,这样比较好
tokenVec.push_back(tokenStk.top());
tokenStk.pop();
}
string ret;
if (tokenVec.empty()) ret.append(, '/');
for (int i = tokenVec.size() - ; i >= ; --i){
ret.append(, '/');
ret.append(tokenVec[i]);
}
return ret;
}
};
PS:应为短的if不喜欢加上{}的原因,找bug找了好久,下次不能继续这个坏习惯,mark一下。
下面是java版本,不得不说java的String的api比c++的要好用太多了,可以用正则表达式分割单词真是爽啊,不用向c++那样做很多次判断了,代码如所示:
public class Solution {
public String simplifyPath(String path) {
String[] pathArr = path.split("[//]+");//首先用正则表达式将整个式子按照//分开
Stack<String> s = new Stack<String>();
for(int i = 0; i < pathArr.length; ++i){
if(pathArr[i].equals("..")){
if(!s.isEmpty())
s.pop();
}else if(pathArr[i].equals(".")){
continue;
}else{
if(!pathArr[i].equals(""))//split有可能会分割出来空白的字符,这里应该注意并且剔除
s.push(pathArr[i]);
}
}
String ret = new String("");
while(!s.isEmpty()){
ret = "/" + s.pop() + ret;
}
if(ret.length() == 0)
ret += "/";
return ret;
}
}
最新文章
- springMVC操作mongoDB增删改查
- js函数的调用问题
- [原]Ubuntu 14.04编译Android Kernel
- IOS-一步一步教你自定义评分星级条RatingBar ——转载的
- java连接access数据库
- poj 3628 (搜索or背包)
- 语音信号处理之(三)矢量量化(Vector Quantization)
- python 学习 异常处理
- 深入理解Java常用类-----时间日期
- 西电2017ACM网络赛
- postman 第6节录制case
- 1017. Queueing at Bank (25) - priority_queuet
- Redis分布式锁的try-with-resources实现
- nginx问题相关记录
- Codeforces 1120D Power Tree [最小生成树]
- tomcat配置接口访问时间
- PHP常用函数归类【持续整理中......】
- CPU-bound(计算密集型) 和I/O bound(I/O密集型)
- JS事件(二)事件对象
- 把javabean复制到另一个javabean 使用BeanUtils.copyProperties(a,b) 复制