Write a program to check whether two strings are an anagram of each other.
Anagram Strings: Two strings are said to be anagram if the characters' frequency is the same in both the strings.
Example 1:
Input: str1="abc" , str2="cab"
Output: Strings are anagram
Example 2:
Input: str1="aacc" , str2="ccac"
Output: String are not anagram
Approach
Java
import java.util.HashMap;public class StringAnagram {public static void main(String[] args) {String str1 = "aacc";String str2 = "ccac";if (checkStrAnagram(str1, str2)) {System.out.println("Strings are anagram");} else {System.out.println("Strings are not anagram");}}// Method used for check string anagarmprivate static boolean checkStrAnagram(String str1, String str2) {// hold char frequencyHashMap<Character, Integer> map = new HashMap<>();// Base case // null checkif (str1.length() == 0 && str2.length() == 0)return true;if (str1 == null || str1.length() == 0 ||str2 == null || str2.length() == 0) {return false;}// calculate frequency of str1for (int i = 0; i < str1.length(); i++) {map.put(str1.charAt(i),map.getOrDefault(str1.charAt(i), 0) + 1);}// check frequency of str1 is equals of str2for (int i = 0; i < str2.length(); i++) {// if element not contain in str1if (!map.containsKey(str2.charAt(i)))return false;// if frequency not equalif (map.get(str2.charAt(i)) == -1)return false;map.put(str2.charAt(i),map.getOrDefault(str2.charAt(i), 0) - 1);}// worst case : check remaining frequencyfor (Character ch : map.keySet()) {if (map.get(ch) > 0) {return false;}}return true;}}
C++
#include <bits/stdc++.h>using namespace std;//function to check the//given strings are anagram or notbool checkAnagram(string str1,string str2){int len1=str1.size();int len2=str2.size();if(len1!=len2)return false;unordered_map<char,int> ump;for(int i=0;i<len1;i++){ump[str1[i]]++;}for(int i=0;i<len2;i++){if(ump[str2[i]]==0)return false;elseump[str2[i]]--;}for(auto it=ump.begin();it!=ump.end();it++){if(it->second>0)return false;}return true;}int main(){string str1="aacc";string str2="ccac";if(checkAnagram(str1,str2))cout<<"Srings are anagram\n";elsecout<<"String are not anagram\n";return 0;}
No comments:
Post a Comment