-1

这个程序接受输入的字符串数量,然后是实际的字符串。输出应该是所有字符串的公共字符数。

约束是:

  1. 字符串数 <= 100
  2. 字符串长度 <= 100

例如..

输入:

3 abc bcd cde

输出:

1

因为只有c对所有字符串都是通用的。

当与小输入一起使用时,它可以提供正确的输出。

但是当与这样的大字符串一起使用时:https ://hr-testcases.s3.amazonaws.com/2223/input19.txt?AWSAccessKeyId=AKIAINGOTNJCTGAUP7NA&Expires=1408959130&Signature=E%2BMnR6MA0gQNkuWHMvc70eCL5Dw%3D&response-content-type=text%2Fplain

它给出了 58 而不是 19 的错误输出。

这是我的代码:

#include<stdio.h>
#include<string.h> 

void main(){
    int n,i,j,count=0;
    char s[100][100];
    scanf("%d",&n);
    for(i=0;i<n;i++){
        scanf("%s",s[i]);
    }
    int t;
    int l = strlen(s[0]);
    for(i=0;i<l;i++){
        t=0;
        for(j=1;j<n;j++){
            if(strchr(s[j],s[0][i])!='\0'){
                t++;
            }
        }
        if(t==n-1)
            count++;
    }
    printf("%d",count);
}
4

1 回答 1

0

当您遍历第一个字符串的字符时,您可能会多次找到相同的字符。

这意味着在第一个字符串中发现多次的常见字符将被计算多次。

这就是导致您的程序计算 58 而不是 19 的原因。

检查下面对您的程序的一些快速更新 - 它处理第一个字符串中的重复项。

该程序在您的 100 个字符串的测试用例中计算 19。

#include<stdio.h>
#include<string.h> 

void main(){
    int n,i,j/*,count=0*/;
    int count[26] = {0};  /* counter per char */
    char s[100][101];
    scanf("%d",&n);
    for(i=0;i<n;i++){
        scanf("%s",s[i]);
    }
    int t;
    int l = strlen(s[0]);
    for(i=0;i<l;i++){
        t=0;

        /* convert char to integer - assuming lowercase char only */             
        int char_index = s[0][i] - 'a'; 

        for(j=1;j<n;j++){
            if(strchr(s[j],s[0][i])!='\0' && count[char_index] == 0){
                t++;
            }
        }
        if(t==n-1)
            count[char_index] = 1;
            /* count++; */
    }
    /* count how many chars are 1*/
    int count_n = 0;
    int index;
    for (index = 0; index < 26; index ++)
    {
        if (count[index] == 1)
            count_n ++;
    }
    printf("\n\n%d",count_n);
}
于 2014-08-25T09:23:31.267 回答