From e97dce5b0b90ddea979feff110120b44a5114124 Mon Sep 17 00:00:00 2001 From: Akash Negi <55234838+NegiAkash890@users.noreply.github.com> Date: Tue, 8 Jun 2021 16:09:49 +0530 Subject: [PATCH] chore(CPlusPlus): created anagram (#336) * Created anagram.cpp * [Update] : anagram.cpp * [Fixed] : typo * [Updated] ; readme.md --- algorithms/CPlusPlus/README.md | 1 + algorithms/CPlusPlus/Strings/anagram.cpp | 34 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 algorithms/CPlusPlus/Strings/anagram.cpp diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index e94fc7a5..4b4b891d 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -57,6 +57,7 @@ 2. [All subsequence of a string (Recursion) ](Strings/sequence.cpp) 3. [String reversal](Strings/string-reverse.cpp) 4. [String tokanisation](Strings/string-tokeniser.cpp) +5. [Anagram check](Strings/anagram.cpp) ## Trees 1. [Creating Binary Tree](Trees/build-binary-tree.cpp) diff --git a/algorithms/CPlusPlus/Strings/anagram.cpp b/algorithms/CPlusPlus/Strings/anagram.cpp new file mode 100644 index 00000000..89e8e779 --- /dev/null +++ b/algorithms/CPlusPlus/Strings/anagram.cpp @@ -0,0 +1,34 @@ +/* + Description : To check whether a string is anagram or not. + Anagram: An anagram is a word or phrase formed by rearranging the letters in another word or phrase + Approach:Using characters as array index +*/ +#include +using namespace std; + +bool isAnagram(string s1, string s2) { + int temp[256] = { 0 }; + for (int i = 0; i < s1.length(); i++) { //Idea : Here we are using characters of the string as indexes. + temp[s1[i]]++; //Each character(except same) will have different position allocated in the temp array + temp[s2[i]]--; //Here, characters of first string are incrementing the count at s1[i] position and characters + //of second string are decrementing the count at s2[i] position + } + for (int i = 0; i < 256; i++) { + if (temp[i] > 0) { //If we found any index in temp array with value greater than 0 then the + return false; //strings are not anagram + } + } + return true; //If values at all the indexes of temp array is zero, this will indicate that all characters +} //in second array cancelled the count of characters in the first array +int main() { + string s1 ; + string s2 ; + cin>>s1; + cin>>s2; + string ans = isAnagram(s1, s2) ? "YES" : "NO"; + cout << ans << endl; + return 0; + //Ex : s1= "abc" s2="abd" + //Output : NO + //Time Complexity : O(n), where n is the length of string +}