string - What is the difference between these two loops in C++? -


what difference between these 2 loops? working on few competitive programming challenges, everytime using first loop variant failing , when changed second kind of loop passes tests:

loop variant 1:

for(int j=0; j<str1.length() ; j++) {     char ch =  str1[j]     int diff = ch-'a';     arr1[diff]++; } 

loop variant 2:

for(int =0; i<str1.length() ;i++) {     arr1[str1[i]-'a']++; } 

i understand silly question please patient, want clear why first 1 not working.


example: find minimum number of character deletions required 2 given strings anagrams

input: cde abc

output: 4

incorrect code

void mindeletions(string str1, string str2) {     if(str1 == str2){         cout << 0 << endl;         return;     }      int arr1[26] = {0};     int diff,diff1;     for(int =0; i<str1.length() ;i++) {         char ch =  str1[i];         diff = ch-'a';         arr1[diff]++;     }      int arr2[26] = {0};     for(int j=0; j<str2.length() ; j++) {         char ch =  str2[j];         diff1 = ch-'a';         arr2[diff]++;     }     int count = 0;     for(int k=0; k<26 ; k++){         if(arr1[k]!=arr2[k]){             count += abs(arr1[k]-arr2[k]);         }     }      cout << count << endl; }   int main() {     string str1,str2;     cin >> str1;     cin >> str2;     mindeletions(str1,str2);     return 0; } 

example of test case fails

input:

 fcrxzwscanmligyxyvym  jxwtrhvujlmrpdoqbisbwhmgpmeoke 

output:

30 

cant it? compared second loop variant, that works fine, there no explicit int diff here source of confusion (see below):

int arr1[26] = {0}; int diff, diff1; for(int = 0; < str1.length() ; i++){     char ch =  str1[i];     diff = ch - 'a'; //  ^^^^     arr1[diff]++; //       ^^^^ }  int arr2[26] = {0}; for(int j = 0; j < str2.length() ; j++){     char ch =  str2[j];     diff1 = ch - 'a'; //  ^^^^^     arr2[diff]++; //       ^^^^ } 

p.s. closely, both loops use same index! i.e. it's not updated in second loop after gets value in first loop.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -