Is a Valid Anagram With Java


The challenge

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

The solution in Java code

class Solution {
    // Take in both strings
    public boolean isAnagram(String s, String t) {
        
        // convert to character array
        char[] c1 = s.toCharArray();
        char[] c2 = t.toCharArray();
        
        // sort the array
        Arrays.sort(c1);
        Arrays.sort(c2);
        
        // convert back to a string
        String s2 = new String(c1);
        String t2 = new String(c2);
        
        // compare them and return a boolean
        if (s2.equals(t2)) return true;
        return false;
        
    }
}