strcspn 본문

Programming/Questions

strcspn

halatha 2008. 8. 28. 15:20
http://www.careercup.com/question?id=58086

Given a function
int strcspn(char * source, char * search)

code the most efficient way to return the index of first character that matches in the source string.
eg#

source ="ttbbcca"
search ="ggabba"

the returned value is 6 since the first match "a" occurs at 6th index in source string.

* 실제 strcspn 함수의 동작은 문제와는 다름
size_t strcspn (const char *string, const char *stopset) [Function]
The strcspn (\string complement span") function returns the length of the initial substring of string that consists entirely of characters that are not members of the set specified by the string stopset. (In other words, it returns the offset of the first character in string that is a member of the set stopset.)
For example,
strcspn ("hello, world", " \t\n,.;!?")
-> 5

// 사이트에 winia라는 사람이 올린 방법
int strcspn(char* source, char* search)
{
    int i, index[256];
    for(i=0;i<256;i++)
        index[i]=0;
    char* ptr=source;
    int idx=0;
    while(ptr[idx])
    {
        if(!index[ptr[idx]])
            index[ptr[idx]]=idx;
        idx++;
    }
    ptr=search;
    idx=0;
    while(ptr[idx])
    {
        if(index[ptr[idx]])
            return index[ptr[idx]];
        idx++;
    }
    return -1;
}

// 내가 만든 방법
int strcspn(char* source, char* search)
{
    int    i;
    int    z_iArrRes[26];

    //    26개의 각 character별 index를 표시하는 array를 -1로 초기화
    for ( i = 0; i < 26; ++i )
        z_iArrRes[i] = -1;

    //    source string에 있는 문자의 index를 z_iArrRes에 입력
    for ( i = 0; i < strlen(source); ++i )
        if ( z_iArrRes[*(source + i) - 'a'] == -1 )
            z_iArrRes[*(source + i) - 'a'] = i;

    //    z_iArrRes에서 -1이 아닌 첫 번째 것의 값을 반환
    for ( i = 0; i < strlen(search); ++i )
        if ( z_iArrRes[*(search + i) - 'a'] != -1 )
            return    z_iArrRes[*(search + i) - 'a'];

    return    -1;
}
Comments