[leetcode-71]Simplify Path(C)

问题描述:
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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值