问题描述:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
分析:使用C语言的strtok函数可以很方便的对字符串进行切割,然后利用strcmp函数对字符串进行比较,如果比对结果为.那么不做任何事。如果为..,那么就删除res中最后一个加入项(到/为止)。如果为其他字符,直接加入即可。
测试用例中有“///”和”/”,strtok函数似乎直接将这两者过滤掉了,所以返回值为空。这时候要加判断,res如果为空时,返回”/”,放心,如果是正常的字符的话,长度不会为0的。
代码如下:4ms
void removeChars(char *res,int index){
while(index>=0&&res[--index]!='/');
res[index] = '\0';
}
char* simplifyPath(char* path) {
int length = strlen(path);
char *res = (char *)calloc(length,sizeof(char));
int resIndex = 0;
int i = 0;
char *tmpSplim;
while((tmpSplim=strtok(path,"/"))!=NULL){
if(strcmp(tmpSplim,".")==0||strlen(tmpSplim)==0);
else if(strcmp(tmpSplim,"..")==0){
removeChars(res,resIndex);
}
else {
res[resIndex++] = '/';
strcpy(res+resIndex,tmpSplim);
}
resIndex = strlen(res);
path = NULL;
}
if(!resIndex){
res[resIndex] = '/';
res[resIndex+1] = '\0';
}
return res;
}