2022年10月25日 星期二

[833] Find And Replace in String

真的很棒, 寫完這題我懷疑我真的會string or pointer 嗎.....(倒地)
以這個出錯的頻率, 應該要450分鐘才寫的完吧(搥牆)
不過看看C的submit , 發現大家都寫很長XD
我感到安慰  XDDDDDD
這題太折騰人了, 明天再看看有沒有什麼厲害的解法吧.....(昏)

char * findReplaceString(char * s, int* indices, int indicesSize, char ** sources, int sourcesSize, char ** targets, int targetsSize){
    int sLen=strlen(s);
    int *sortIndex = malloc (sizeof(int)*sLen);
    char *out = malloc (sizeof(char)* (sLen*50)+1);
    memset (sortIndex,-1,sLen);
    for(int i=0;i<indicesSize;i++)
        sortIndex[indices[i]]=i;
    int keepSLen = sLen;
    int outLen=0;
    for(int i=0;i< keepSLen;i++)
    {
        if(sortIndex[i]<0)
        {
            out[outLen++]=s[i];
            continue;
        }
        int targetIdx = indices[sortIndex[i]];
        int tarLen = strlen(targets[sortIndex[targetIdx]]);
        int orgLen = strlen(sources[sortIndex[targetIdx]]);
        if (orgLen > sLen-outLen)
        {
            out[outLen++]=s[i];
            continue;            
        }
        int cmp =0;
        for (cmp=0; cmp < orgLen;cmp++)
        {
            if (s[i+cmp] == sources[sortIndex[targetIdx]][cmp])
                continue;
            else
                break;
        }
        if(cmp ==orgLen)
        {   //replace
            for(int k=0;k<tarLen;k++)
                out[outLen++]=targets[sortIndex[targetIdx]][k];   
            sLen+=(tarLen-orgLen);
            i+=(cmp-1);
        }
        else
        {
            out[outLen++]=s[i];
            continue;
        }            
    }
    out[sLen]='\0';
    return out;   
}

沒有留言:

張貼留言