Simplify Path
来源:互联网 发布:整形医院网络咨询技巧 编辑:程序博客网 时间:2024/05/23 19:15
题目大意:给一个Unix风格的文件的绝对路径,将其进行简化。例如:
路径 "/home/", => "/home"
注意事项:"..."在Unix下是合法的路径名。路径中出现连续的“///”需要将其简化为“/”。“/../../..”简化之后的路径是“/”
路径 "/home/", => "/home"
路径 "/a/./b/../../c/", => "/c"
思路分析:利用栈。
代码如下:
char* simplifyPath(char* path) { int i, t=1; int len = strlen(path); path[0] = '/'; for(i=1; i<len; i++) { if(path[i]=='.' && ((i+1<len && path[i+1]=='/') || path[i+1]=='\0')) { //处理"." i = i + 1; } else if(path[i]=='.' && i+1<len && path[i+1]=='.' && ((i+2<len && path[i+2]=='/') || path[i+2]=='\0')) { //处理“..” i = i + 2; t = t - 2 < 0? 0: t-2; while(path[t]!='/') { // 出栈,退回到上一级目录处 t--; } t++; } else if(path[i]=='/') { //过滤连续的斜杠(比如“////”)的情况 continue; } else { //其他情况则进行入栈操作 do { path[t++] = path[i++]; } while(i<len && path[i]!='/'); path[t++] = path[i]; } } if(t>1) { //如果最后只剩下“/”则特殊处理一下。 path[t-1] = '\0'; } else { path[t] = '\0'; } return path;}
注意事项:"..."在Unix下是合法的路径名。路径中出现连续的“///”需要将其简化为“/”。“/../../..”简化之后的路径是“/”
上面的代码略显繁琐,如果更好地处理一下代码逻辑可能会更简洁一点。
0 0
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- 关于UIScrollView不能响应UITouch事件的解决办法
- 用户不在 sudoers 文件中 此事将被报告
- Monodb 入门
- android.mk加入三方jar
- android自定义的TextView,实现跑马灯效果
- Simplify Path
- const类型参数的对象引用和const成员函数
- jQuery之动画
- Android音频系统之AudioTrack(一)
- 【鸟瞰】C#的学习
- 第16周 项目2 - 大数据集上排序算法性能的体验
- “#ifdef __cplusplus extern "C" { #endif”的定义(转)
- 遍历map集合
- Android 高级开发笔记 第一章 Activity的生命周期探索