chore(CPlusPlus): created anagram (#336)

* Created anagram.cpp

* [Update] : anagram.cpp

* [Fixed] : typo

* [Updated] ; readme.md
pull/348/head
Akash Negi 2021-06-08 16:09:49 +05:30 committed by GitHub
parent fd43c38320
commit e97dce5b0b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 0 deletions

View File

@ -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)

View File

@ -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<bits/stdc++.h>
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
}