The below code asks the user to enter in two strings from there it checks to see
ID: 667409 • Letter: T
Question
The below code asks the user to enter in two strings from there it checks to see if the following are anagrams or not. For this code. I was wondering what would the Data Structure be on the following code? The program is in C++. Please Explain the Data Structures as well as point them out. Also besides this given code is there another method that could be used in order to get the same results?
#include
#include
#include
#include
using namespace std;
bool AnagramCheck(const string&, const string&);
char lower(char c) { return tolower(c); }
bool checkAlnum(char c) { return isalnum(c); }
bool checknotAlnum(char c) { return !checkAlnum(c); }
int main(int argc, char *argv[]) {
string first, second;
while (true) {
cout << endl << "Enter first string: ";
getline(cin, first);
cout << "Enter ssecond string: ";
getline(cin, second);
cout << """ << second << "" is "
<< ((AnagramCheck(first, second) == false) ? "not " : " ")
<< "an anagram of "" << first << """ << endl;
}
return 0;
}
bool AnagramCheck(const string &firstString, const string& secondString) {
bool anagram = false;
string s0(count_if(firstString.begin(), firstString.end(), checkAlnum), ' '),
s1(count_if(firstString.begin(), firstString.end(), checkAlnum), ' ');
// removing unnecessary sysmbols
remove_copy_if(firstString.begin(), firstString.end(), s0.begin(), checknotAlnum);
remove_copy_if(secondString.begin(), secondString.end(), s1.begin(), checknotAlnum);
if (s0.size() == s1.size()) {
//checking length and converting to al lower case
transform(s0.begin(), s0.end(), s0.begin(), lower);
transform(s1.begin(), s1.end(), s1.begin(), lower);
if (s0 != s1) {
//sorting to check for anagram
sort(s0.begin(), s0.end());
sort(s1.begin(), s1.end());
anagram = (s0 == s1);
}
}
return anagram;
}
Explanation / Answer
There are two algorithms with the help of which you can solve this problem:
1)Use Sorting:
1.1) Compare the length of two strings and if the length of the strings is same then go to step 1.2 else return 0.
1.2) Now, sort the strings and compare if they are equal or not. If they are equal return true else return false.
2) Count Array
2.1) In this method you will be maintaining the count array of the string in the hashmap.
2.2) Initialise one hashmap which contains all the alphabets as the key and corresponding value 0.
2.3) traverse first string and for each character you encounter increase the count by one of the corresponding character in hashmap.
2.4) traverse second string for each character you encounter decrease the count by one of the corresponding character in hashmap.
2.5) traverse the hashmap and if you see any character with value not equal to zero than return false else true.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.