anagram
Anagram

An anagram is a rearrangement of the letters of one word or phrase to another word or phrase, using all the original letters exactly once.

Write a function to check whether two given strings are anagram of each other or not. For example, abcd and dabc are anagram of each other.

Kotlin program to strings are anagram of each other or not


import java.util.*

fun main(args: Array) {
    var str1 = "mother in law";
    var str2 = "women hitler";

    var isAnagram = Arrays.equals(str1.chars().sorted().toArray(),
            str2.chars().sorted().toArray());

    if (isAnagram)
        System.out.println("Strings are Anagrams of each other");
    else
        System.out.printf("Strings are not Anagrams of each other");
}


Output


Strings are Anagrams of each other

Anagrams using Maps
  • We populate a HashMap object by iterating over the character representation of the first string (one) and associating each of the keys with the frequency of the character under consideration.
  • Then we iterate over the character representation of the second string (two) and reduce the frequency of each of the found keys, if it becomes 0, that particular key is removed from the structure, and in case the key is not found at all, false is returned.
  • In the end, the result of whether the HashMap is empty or not is returned, because if it is, then that means that all the characters and the associated frequencies got cancelled out and the strings are anagrams.

import java.util.HashMap

fun main(args: Array<String>) {
    val three = "dorm"
    val four = "mordor"
    //LOTR reference
    println(areAnagrams(three, four))

    val five = "tom marvolo riddle"
    val six = "iam lord voldemort"
    //the famous Harry Potter reference
    println(areAnagrams(five, six))
}

private fun areAnagrams(one: String, two: String): Boolean {
    val map = HashMap<Char, Int>()

    for (c in one.toCharArray())
        if (map.containsKey(c))
            map[c] = map[c]!! + 1
        else
            map[c] = 1

    for (c in two.toCharArray())
        if (!map.containsKey(c))
            return false
        else {
            map[c] = map[c]!! - 1

            if (map[c] == 0)
                map.remove(c)
        }
    return map.isEmpty()
}

Output of program


false
true

 
Join My Facebook Group
Join Group
 

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions