1. 程式人生 > >71. 簡化路徑(C++)

71. 簡化路徑(C++)

給定一個文件 (Unix-style) 的完全路徑,請進行路徑簡化。

例如,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

邊界情況:

  • 你是否考慮了 路徑 = "/../" 的情況?
    在這種情況下,你需返回 "/" 。
  • 此外,路徑中也可能包含多個斜槓 '/' ,如 "/home//foo/" 。
    在這種情況下,你可忽略多餘的斜槓,返回 "/home/foo" 。

 

#include "stdafx.h"
#include<string>
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
string simplifyPath(string path) {
	vector<string> s;
	int j = 0;
	int len = path.size();
	if (len == 0) return path;	
	for (int i = 0; i < len; i++)
	{
		vector<char> temp;
		while(i < len && path[i] != '/')
		{
			temp.push_back(path[i++]);
		}
		if (temp.size() > 0)
		{
			string stemp;
			for (int k = 0; k < temp.size(); k++)
			{
				stemp += temp[k];
			}
			if (stemp.compare("..") == 0 && s.size() > 0)//如果為..則刪除上層目錄
			{
				s.erase(s.end()-1);
			}	
			if (stemp.compare(".") != 0 && stemp.compare("..") != 0)//compare相同返回0,既不為.也不為..
			{
				s.push_back(stemp);
			}
		}
	}
	if (s.size() == 0) return "/";
	string res;
	vector<int> arr(s.size());
	for (int i = 0; i < s.size(); i++)
	{
		res += "/";
		res += s[i];
	}
	return res;
}
//int main()
//{
//
//	string  path1 = "/home/";
//	string	path2 = "/a/./b/../../c/";
//	string	path3 = "/a/../../b/../c//.//";
//	string	path4 = "/a//b////c/d//././/..";
//	string	path5 = "////";
//	string path = simplifyPath(path5);
//	getchar();
//	return 0;
//
//}