Is a Valid Anagram with Java

0 min read 142 words

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;
        
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags