Finding common characters in two strings

前端 未结 13 2589
终归单人心
终归单人心 2020-12-15 14:09

I am coding for the problem in which we got to count the number of common characters in two strings. Main part of the count goes like this

for(i=0; i < st         


        
13条回答
  •  情话喂你
    2020-12-15 14:27

    Following code traverses each sting only once. So the complexity is O(n). One of the assumptions is that the upper and lower cases are considered same.

     #include
    
    int main() {
        char a[] = "Hello world";
        char b[] = "woowrd";
        int x[26] = {0};
        int i;
        int index;
    
        for (i = 0; a[i] != '\0'; i++) {
            index = a[i] - 'a';
            if (index > 26) {
                //capital char
                index = a[i] - 'A';
            }
            x[index]++;
        }
    
        for (i = 0; b[i] != '\0'; i++) {
            index = b[i] - 'a';
            if (index > 26) {
                //capital char
                index = b[i] - 'A';
            }
    
            if (x[index] > 0)
                x[index] = -1;
        }
    
        printf("Common characters in '%s' and '%s' are ", a, b);
        for (i = 0; i < 26; i++) {
            if (x[i] < 0)
                printf("%c", 'a'+i);
        }
        printf("\n");
    }
    

提交回复
热议问题