Given a string we have to check whether two string is anagram of each other or not.and print the result.
So what is anagram of string?
anagram of string is a string that contain same character with diffrent order.
Example:
input:silent
output:listen
Logic:
step 1- make two character array and initilise with 0.
step 2-iterate both the string and increment character array value.
step 3-iterate character array if we get both array are equal then it is anagram.
Code-
#include<bits/stdc++.h> using namespace std; int main() { string s1="listen"; string s2="silent"; int hash1[26]={0}; int hash2[26]={0}; for(int i=0;i<s1.length();i++) { hash1[s1[i]-'a']++; } for(int i=0;i<s2.length();i++) { hash2[s2[i]-'a']++; } int flag=0; for(int i=0;i<26;i++) { if(hash1[i]!=hash2[i]) { flag=1; break; } } if(flag==0) { cout<<"anagram"<<endl; } else { cout<<"not anagram"<<endl; } }
Output:
anagram
Time complexity:0(N)
Space Complexity:O(N)