Java solution O(n) supporting surrogate pairs - smileys, for example


  • 0
    X

    Many of published (and accepted!) solutions will not work with 4-byte characters - aka surrogate pairs. For example, smileys.
    I think, it is a leetcode limitation - nobody can contribute testcase, containing smiley codepoint. Such codepoints doesn't supported by String literals and can be encoded for example with StringBuilder.addCodepoint().

    As a result - my solution beats only 2% java solutions :)

    public boolean isAnagram(String s, String t) {
        return Arrays.equals(sortCodepoints(s), sortCodepoints(t));
    }
    
    private int[] sortCodepoints(String str) {
        if (str == null)
            return new int[0];
        int[] points = str.codePoints().toArray();
        Arrays.sort(points);
        return points;
    }
    

Log in to reply
 

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