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;
}
}

最新文章

  1. springMVC操作mongoDB增删改查
  2. js函数的调用问题
  3. [原]Ubuntu 14.04编译Android Kernel
  4. IOS-一步一步教你自定义评分星级条RatingBar ——转载的
  5. java连接access数据库
  6. poj 3628 (搜索or背包)
  7. 语音信号处理之(三)矢量量化(Vector Quantization)
  8. python 学习 异常处理
  9. 深入理解Java常用类-----时间日期
  10. 西电2017ACM网络赛
  11. postman 第6节录制case
  12. 1017. Queueing at Bank (25) - priority_queuet
  13. Redis分布式锁的try-with-resources实现
  14. nginx问题相关记录
  15. Codeforces 1120D Power Tree [最小生成树]
  16. tomcat配置接口访问时间
  17. PHP常用函数归类【持续整理中......】
  18. CPU-bound(计算密集型) 和I/O bound(I/O密集型)
  19. JS事件(二)事件对象
  20. 把javabean复制到另一个javabean 使用BeanUtils.copyProperties(a,b) 复制

热门文章

  1. 001-ant design pro安装、目录结构、项目加载启动【原始、以及idea开发】
  2. R语言操作mysql上亿数据量(ff包ffbase包和ETLUtils包)
  3. PScc
  4. mysql双向主从同步
  5. LeetCode:二叉树的后序遍历【145】
  6. Linux下的查找命令which、whereis、locate、find(6/20)
  7. 对MySQL数据类型的认识
  8. Keras实现autoencoder
  9. Git服务器的Gitosis安装配置及gitignore的使用方法
  10. Spring核心技术AOP实现原理