Java AC -- not need Array and Map -- bitwise


  • 0
    D
    public class Solution {
    public boolean isAnagram(String s, String t) {
        // if all lowercase alph
        int sum = 0 ; 
        int sProd = 1 ;   
        int tProd = 1 ;
        for(Character i : s.toCharArray())
        {
            sum += i ;
            sProd *= i;
        }
        for(Character i : t.toCharArray())
        {
           sum -= i;
           tProd *= i;
        }
        return sum == 0  && sProd == tProd;
    }}
    

    // or this is kind of cheating

    public class Solution {
    public boolean isAnagram(String s, String t) {
        long sSum  = 0 ;
        for(Character i : s.toCharArray())
        {
            sSum += (i * i * i * i);
        }
        for(Character i : t.toCharArray())
        {
            sSum -= ( i*i *i* i );
        }
        return sSum == 0;
    }}

Log in to reply
 

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