Java solution using sort


  • 16
    B
    public class Solution {
    public boolean isAnagram(String s, String t) 
    {
        char[] sChar = s.toCharArray();
        char[] tChar = t.toCharArray();
        
        Arrays.sort(sChar);
        Arrays.sort(tChar);
        
        return Arrays.equals(sChar, tChar);   
    }
    

    }


  • 3
    C

    I think you will agree that there are a couple of checks missing in your code. Please allow me to modify your code.

    public boolean isAnagram(String s, String t) 
    {
        if(null == s)
          return (t==null);
        if(t==null || s.length() != t.length())
          return false;
        char[] sChar = s.toCharArray();
        char[] tChar = t.toCharArray();
    
        Arrays.sort(sChar);
        Arrays.sort(tChar);
    
        return Arrays.equals(sChar, tChar);   
    }

  • 0
    L

    I thought about this too but sorting it severely reduces the efficiency. The map/ array route is better


  • -1
    Y

    i think the code would be more beautiful if it's modified by this way:
    public boolean isAnagram(String s, String t)
    {
    if(s == null || t == null){
    return s == t;
    }
    char[] sChar = s.toCharArray();
    char[] tChar = t.toCharArray();
    Arrays.sort(sChar);
    Arrays.sort(tChar);
    return Arrays.equals(sChar, tChar);
    }


  • 0
    S

    Beautiful solution!
    I choose HashMap to solve it,but you are more efficient!


  • 0
    L

    @simonhc This is not more efficient. Sorting is O(NlogN), HashMap/Array method O(N)


  • 0
    S

    @lekzeey Oh,sorry,I should use 'pithy'


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.