Algorithms – Part 3: Typed Out Strings (Brute Force)

This time, let’s examine an alternate version of a question that was previously posed: typed-out strings.

Question:

Given two strings str1 and str2, return if they are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Solution:

And here’s a solution I came up with.

import java.util.Arrays;

public class AnagramCheckMyChallenge {

    public static boolean areAnagrams(String str1, String str2){

        str1 = str1.toLowerCase();
        str2 = str2.toLowerCase();

        char[] char1 = str1.toCharArray();
        char[] char2 = str2.toCharArray();

        Arrays.sort(char1);
        Arrays.sort(char2);

        String sorted1 = new String(char1);
        String sorted2 = new String(char2);

        if (sorted1.equals(sorted2)) {
            return true;
        } else {
            return false;
        }

    }

    public static void main(String[] args) {
        String str1 = "listen";
        String str2 = "silent";
        // System.out.println("Are anagrams: " + areAnagrams(str1, str2)); // Output: true
        System.out.println(areAnagrams(str1, str2)); // Output: true
    }
}

Leave a Reply