Java Anagrams

Sort by

recency

|

2495 Discussions

|

  • + 0 comments

    A bit of an odd solution, but the use of primes allows for a mathematic approach that doesn't require sorting and only requires traversing the arrays a single time. Not meaningfully better than storing an int in the index of the char value, but fun!

        static boolean isAnagram(String a, String b) {
            // Complete the function
            
            if(a.length() != b.length()) {
                return false;
            }
            
            a = a.toLowerCase();
            b = b.toLowerCase();
            
            int[] lookupArr = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101};
            int total = 0;
            
            for(int i = 0; i < a.length(); i++) {
                total += lookupArr[a.charAt(i) - 97];
                total -= lookupArr[b.charAt(i) - 97];
            }
            
            if(total == 0) {
                return true;
            }
            return false;
        }
    
  • + 0 comments

    static boolean isAnagram(String a, String b) {

        if(a.length() != b.length())return false;
    
        char[] c1 = a.toLowerCase().toCharArray();
        char[] c2 = b.toLowerCase().toCharArray();
    
        java.util.Arrays.sort(c1);
        java.util.Arrays.sort(c2);        
    
        for(int i=0; i<c1.length; i++){
            if(c1[i]!=c2[i])return false;
        }
    
        return true;
    
  • + 0 comments
        Scanner scan = new Scanner(System.in);
        char[] first = scan.next().toLowerCase().toCharArray();
        char[] second = scan.next().toLowerCase().toCharArray();
        Arrays.sort(first);
        Arrays.sort(second);
    
        if (Arrays.equals(first, second)) {
          System.out.println("Anagrams");
        } else {
          System.out.println("Not Anagrams");
        }
    
  • + 0 comments
    • static boolean isAnagram(String a, String b) {

    •     int[] aChar=new int[27];
      
    •     int[] bChar=new int[27];
      
    •     int length,ac,bc;
      
    •     if((length=a.length())!=b.length())
      
    •         return false;
      
    •     for(int i=0;i<length;i++){
      
    •         if((ac=a.charAt(i))>92)
      
    •             ac -= 32;
      
    •         if((bc=b.charAt(i))>92)
      
    •             bc -= 32;
      
    •         aChar[ac-65]++;
      
    •         bChar[bc-65]++;
      
    •     }
      
    •     for(int i=0;i<27;i++){
      
    •         if(aChar[i]!=bChar[i])
              return false;
      }
      return true;
      

      }

  • + 0 comments

    Why i can´t use streams?. The editor doesn't allow me add imports. Anyone, knows waht it happening?