Simplify Path

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

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

 注意特例: /... 保留  ///   /.../. -> /...  按照规则进行处理

  1. string simplifyPath(string path) {
  2. stringstream is(path);
  3. string dir;
  4. vector<string> dirlst;
  5. while(getline(is,dir,'/')){
  6. if(dir == "..") {
  7. if(dirlst.size()!=0) {
  8. dirlst.pop_back();
  9. }
  10. } else {
  11. if(dir.size()!=0 && dir!=".") {
  12. dirlst.push_back(dir);
  13. }
  14. }
  15. }
  16. string res = "";
  17. if(dirlst.size()==0) {
  18. res += "/";
  19. } else {
  20. for(int i=0;i<dirlst.size();i++) {
  21. res += '/';
  22. res += dirlst[i];
  23. }
  24. }
  25. return res;
  26. }
posted @ 2014-08-17 12:15  purejade  阅读(95)  评论(0编辑  收藏  举报