Conditions of the problem: to create a program that checks whether the given strings are "relatives". Relatives are words that are written with the same characters. An example of such lines is "ram" and "drum". Because This is an Olympiad task, then the execution time and weight are important. For some reason, if there are duplicate characters in the word, not parents go to the conclusion. Can someone explain why this is happening and advise solutions for optimization?

#include <iostream> #include <string> using namespace std; int main() { string s1; string s2; getline(cin, s1); getline(cin, s2); bool isEqual[s2.length()]; bool answ = true; for (int i=0;i<s1.length();i++){ for (int y=0;y<s2.length();y++){ if(s2[y] == s1[i]){ isEqual[y]=true; break; } } } for (int i=0; i < s2.length();i++){ if (isEqual[i] == false){ cout << "not parents"; return 0; } } cout << "parents"; } 
  • one
    It remains to understand your task and what parameter to optimize, and at the same time your ways of estimating this parameter and why the parameter values ​​do not suit you. - Vladimir Martyanov
  • "ram" and "drum" are not suitable for this code - Evgeny Shmidt
  • first decided to use English characters, and only then connect the possibility of processing the Cyrillic alphabet - Bogdan Kіnash

1 answer 1

Well, this is not Unicode :), I would make two arrays of 256 bool elements, and just passing by the words would change the corresponding element to true . Very fast operation. And then I would simply go through the arrays and look at the matching values ​​of the elements - zero or not.

If only full compliance is needed - i.e. the letters of the one and the second must match - like "ram" and "drum", but not "ram" and "donut" - you can simply compare two containers.

something like

 vector<bool> v1(256,false), v2(256,false); for(auto c: s1) v1[c] = true; for(auto c: s2) v2[c] = true; if (v1 == v2) ... 

Here is the working code: https://ideone.com/kY8W3n
Or, if the vectors are confused - like this: https://ideone.com/z6cqOX

  • I'm not sure that this will solve the problem, because it is necessary to check the coincidence of characters as such, and not the correspondence of the two strings. Maybe I did not understand something. I apologize in advance, I am an absolute newcomer to s ++ :) - Bogdan Kinash
  • And I check not the coincidence of strings, but the coincidence of the presence of identical characters in strings. - Harry
  • So far I don’t know how to use vectors, so I ’m not fully aware of the code written - Bogdan Kіnash
  • @Harry oh, I don't like the vector<bool> . Better is the usual char c1[256] ) - pavel
  • @pavel Then like this: ideone.com/z6cqOX - Harry