InterviewSolution
Saved Bookmarks
| 1. |
You are given 2 strings as input. You have to check whether they are anagrams or not. |
|
Answer» Anagrams are those strings that have the same characters occurring an equal number of times in both the strings. However, the order can be different. For example “anagram” and “nagrama” are Anagrams. We will use HashMap to store the frequency of each character of the first string. Then, we will traverse the second string and keep on decrementing the frequency in the HashMap. If for any character in the second string, either the character is not present in the HashMap or its frequency is already 0, we will return false. Else, if we have scanned the entire second String and there are no discrepancies, the two strings will be anagrams. Java Code to check Anagrams import java.util.*;class Main { public static boolean isAnagram(String s1, String s2) { if(s1.length() != s2.length()) return false; HashMap<Character,Integer> fmap = new HashMap<>(); for(int i=0;i<s1.length();i++) { int ofreq = fmap.getOrDefault(s1.charAt(i),0); fmap.put(s1.charAt(i),ofreq+1); } for(int i=0;i<s2.length();i++) { if(!fmap.containsKey(s2.charAt(i)) || fmap.get(s2.charAt(i)) == 0) { return false; } else { int ofreq = fmap.get(s2.charAt(i)); fmap.put(s2.charAt(i),ofreq-1); } } return true; } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); String str1 = scn.nextLine(); String str2 = scn.nextLine(); if(isAnagram(str1,str2)) System.out.println(true); else System.out.println(false); } } Sample Output When the strings are anagrams Input:anagram nagrama Output: true Input: anagram nagrame Output: false
|
|