SRM 405 DIV1 Easy - RelativePath

問題


http://community.topcoder.com/stat?c=problem_statement&pm=9760&rd=12177

解き方


システムテストで落ちないようコーナーケースでの検討が必要。
可能であればそれぞれのパスについてディレクトリを取り出して
比較するのが確実。

コード


class RelativePath {

public: string makeRelative(string path, string currentDir) {
string str="";

while(!path.empty() && !currentDir.empty()){
if(path[0]=='/'&&currentDir[0]=='/'){
path=path.substr(1),currentDir=currentDir.substr(1);
}

string s1="",s2="";
int cur=0;
while(cur<path.size() && path[cur]!='/')s1+=path[cur],cur++;
cur=0;
while(cur<currentDir.size() && currentDir[cur]!='/')s2+=currentDir[cur],cur++;

if(s1!=s2 || s1.empty() || s2.empty())break;
path=path.substr(s1.size());
currentDir=currentDir.substr(s1.size());

}

if(!currentDir.empty()){
str+="../";
for(int i=0;i<currentDir.size();i++){
if(currentDir[i]=='/')str+="../";
}
}

if(!path.empty() && path[0]=='/')path=path.substr(1);
str+=path;

return str;
}

};

Share this

Related Posts