Check Anagram Strings
C++
Medium
4 views
Problem Description
Check if two strings have same characters but different order.
Real Life: "listen" and "silent" are anagrams.
Step-by-Step Logic:
1. Count frequency of each character in both strings
2. If all frequencies match, they are anagrams
3. Or sort both strings and compare
4. Return result
Official Solution
void string_q10_anagram() {
string str1 = "listen";
string str2 = "silent";
if(str1.length() != str2.length()) {
cout << "NOT anagrams (different length)" << endl;
return;
}
int freq[26] = {0};
// Count characters in first string
for(int i = 0; i < str1.length(); i++) {
freq[str1[i] - 'a']++;
}
// Subtract characters from second string
for(int i = 0; i < str2.length(); i++) {
freq[str2[i] - 'a']--;
}
// Check if all frequencies are zero
bool isAnagram = true;
for(int i = 0; i < 26; i++) {
if(freq[i] != 0) {
isAnagram = false;
break;
}
}
if(isAnagram) {
cout << str1 << " and " << str2 << " are ANAGRAMS" << endl;
} else {
cout << str1 << " and " << str2 << " are NOT anagrams" << endl;
}
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!