We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
/*
* Complete the 'anagram' function below.
*
* The function is expected to return an INTEGER.
* The function accepts STRING s as parameter.
*/
int anagram(string s) {
int n = s.length();
// If the length is odd, it's impossible to split into two equal halves.
if (n % 2 != 0) {
return -1;
}
int half_len = n / 2;
string s1 = s.substr(0, half_len);
string s2 = s.substr(half_len);
// Frequency arrays for characters 'a' through 'z'
vector<int> freq1(26, 0);
vector<int> freq2(26, 0);
// Populate frequency for s1
for (char c : s1) {
freq1[c - 'a']++;
}
// Populate frequency for s2
for (char c : s2) {
freq2[c - 'a']++;
}
int changes = 0;
// Compare frequencies to find characters that need to be changed in s1
// We only need to count characters that are in s1 but not (or less) in s2
for (int i = 0; i < 26; ++i) {
if (freq1[i] > freq2[i]) {
changes += (freq1[i] - freq2[i]);
}
}
return changes;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string q_temp;
getline(cin, q_temp);
int q = stoi(ltrim(rtrim(q_temp)));
for (int q_itr = 0; q_itr < q; q_itr++) {
string s;
getline(cin, s);
int result = anagram(s);
fout << result << "\n";
}
fout.close();
return 0;
Anagram
You are viewing a single comment's thread. Return to all comments →
c++ answer
include
using namespace std;
string ltrim(const string &); string rtrim(const string &);
/* * Complete the 'anagram' function below. * * The function is expected to return an INTEGER. * The function accepts STRING s as parameter. */
int anagram(string s) { int n = s.length();
}
int main() { ofstream fout(getenv("OUTPUT_PATH"));
}
string ltrim(const string &str) { string s(str);
}
string rtrim(const string &str) { string s(str);
}