2017-07-22 78 views
-5

我有两个字符串a,b分别等长为l1,l2。我想返回给定两个字符串的常用字母数。例如,a ='ABC'和b ='CDE'。我的算法应该返回1,因为只有'C'是两个字符串中的常见字母,但它返回26。任何人都可以请解释为什么?以下是我的算法。算法来检查字符串匹配

for(i=0;i<l1;i++) 
    { 
     for(j=0;j<l2;j++) 
     { 
      if(a[i]==b[j]) 
      { 
       found++; 
      } 
     } 
    } 
+0

发现被声明为整型 – user4532954

+0

...并设置为零,太? – deamentiaemundi

+2

你初始化了'int found = 0;'? – Rabbid76

回答

-4
It's return 1 
char a[3]={'a','b','c'}; 
     char b[3]={'c','d','e'}; 
    int found=0,l1=3,l2=3; 
     for(int i=0;i<l1;i++) 
     { 
      for(int j=0;j<l2;j++) 
      { 
       if(a[i]==b[j]) 
       { 
        found++; 
       } 
      } 
     } 
+0

我认为他们正在寻找解释,而不是确认他们的代码应该工作。出于某种原因,它不适用于OP,但该人员需要提供更多的细节以获得适当的帮助。见[mcve]。 – CDahn

0

你的算法将失败的标准。如果字符串是'CCC',很容易看到会发生什么。

这样做:

int letters[26]={0}; 
int both[26]={0}; 

for(int i=0; i<l1; i++) 
    letters[a[i]-'A']=1; 

for(int i=0; i<l2; i++) 
    if(letters[b[i]-'A']) 
     both[b[i]-'A']=1; 

int found=0; 

for(int i=0; i<26; i++) 
    found+=both[i]; 
+0

你可以去除'for(int i = 0; i <26; i ++) letters [i] = 0;'并做int letters [26] = {0};' –

+0

谢谢。还修复了一个错误。 – klutt

0
// with this code I preferred to convert all char as an ascii code. //Because it is more simpler to compare int value than with 2 for statement //.it has compared if chars are similar ,increase the number of sayi,then //print the equal char of these code 
int main(){ 
char a[]="ABC"; 
char b[]="CDE"; 
    int sizeofa=sizeof(a)-1; 
    int sizeofb=sizeof(b)-1; 
    int sayi=0; 
    int asciia; 
    int asciib; 
    for (int i=0; i<sizeofa;i++) 
    { 
    for (int j=0; j<sizeofb; j++) 
    { 
     asciia=a[i]; 
     asciib=b[j]; 
    if (asciia == asciib) 
     sayi++; 
    } 

    } 
    printf("%d",sayi); 
} 
+1

'sizeof stringarray - 1'通常写成'strlen(stringarray)'(编译器会(希望)优化到相同的常量)。 – pmg

+0

我尝试了以下方式相同的代码,但我得到的输出为26而不是4. – user4532954

+0

当我试着这段代码给了我1.可能问题在于转换为ascii。 –