Skip to content

Instantly share code, notes, and snippets.

@AbdullahMagat
Created July 26, 2018 19:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save AbdullahMagat/1c2d64668539daad3885f39a09cb4136 to your computer and use it in GitHub Desktop.
Save AbdullahMagat/1c2d64668539daad3885f39a09cb4136 to your computer and use it in GitHub Desktop.
Hackerrank Java Anagrams Solution
import java.util.Scanner;
public class Solution {
static boolean isAnagram(String a, String b) {
// // once you declare a.toUppercase you should assign it to a. you cannot define it as just a.toUppercase...
// //I solved it with the long way however I could put a and b in a character array and then use Arrays.sort(arrayname). after this steps convert them to string and check if they are equel.
a=a.toUpperCase();
b=b.toUpperCase();
boolean ret = false;
StringBuilder c= new StringBuilder(b);
if(a.length()==b.length()){
for(int i=0; i<a.length();i++){
for(int j=0; j<c.length();j++){
if(a.charAt(i)==c.charAt(j)){
c.deleteCharAt(j);
if(i==a.length()-1 && c.length()==0){
ret=true;
break;
}
break;
}
}
}
}return ret;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String a = scan.next();
String b = scan.next();
scan.close();
boolean ret = isAnagram(a, b);
System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
}
}
@Ahmedsaka
Copy link

Nice one, thanks a lot Abdullah..................

@RYANSI
Copy link

RYANSI commented Aug 4, 2020

thx

@chalauri
Copy link

chalauri commented Oct 1, 2020

That's slow algorithm

@programmarsks
Copy link

import java.util.Scanner;

public class Solution {

static boolean isAnagram(String c, String d) {
  
  String a=c.toLowerCase();
  String b=d.toLowerCase();
  int count=0;
  int count2=0;

  if(a.length()!=b.length())
  {
      return false;
  }

  for(int i=0; i<a.length(); i++)
  {
      char ch=a.charAt(i);
      for(int j=0; j<a.length(); j++)
      {
          if(a.charAt(j)==ch)
          count++;
          if(b.charAt(j)==ch)
          count2++;
      }
      if(count!=count2)
      {
      return false; 
      }
  }
  return true;
}

public static void main(String[] args) {

@anushree71199
Copy link

what's the use of string builder? can anyone please explain it to me?

@RYANSI
Copy link

RYANSI commented Jul 14, 2021

StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop
StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations.

Strings should always be used unless string builders offer an advantage in terms of simpler code (see the sample program at the end of this section) or better performance. For example, if you need to concatenate a large number of strings, appending to a StringBuilder object is more efficient.

Length and Capacity
The StringBuilder class, like the String class, has a length() method that returns the length of the character sequence in the builder.

Unlike strings, every string builder also has a capacity, the number of character spaces that have been allocated. The capacity, which is returned by the capacity() method, is always greater than or equal to the length (usually greater than) and will automatically expand as necessary to accommodate additions to the string builder.

@RYANSI
Copy link

RYANSI commented Jul 14, 2021

@mearjuntripathi
Copy link

import java.io.;
import java.util.
;

public class Solution {
public static String lvalue(String s){
char str[]=new char[s.length()];
str=s.toCharArray();
char temp;
for(int i=0;i<s.length();i++){
for(int j=0;j<s.length()-1;j++){
temp=str[j+1];
if(str[j]>str[j+1]){
str[j+1]=str[j];
str[j]=temp;
}
}
}
String ss = new String(str);
return ss;
}
public static void main(String[] args) {
String str1,str2;
Scanner in = new Scanner(System.in);
str1=in.next();
str2=in.next();
str1=str1.toLowerCase();
str2=str2.toLowerCase();
if(str1.length()==str2.length()){
str1=lvalue(str1);
str2=lvalue(str2);
if(str1.equals(str2))
System.out.println("Anagrams");
else
System.out.println("Not Anagrams");
}
else
System.out.println("Not Anagrams");
}
}

@pancudaniel7
Copy link

A much more simple solution:

private static boolean isAnagram(String a, String b) {
    if (a.length() != b.length()) {
        return false;
    }
    a = a.toLowerCase();
    b = b.toLowerCase();
    
    for (int i = 0; i < b.length(); i++) {
        a = a.replaceFirst(String.valueOf(b.charAt(i)), "");
    }

    return a.isEmpty() ? true : false;
}

@rof20004
Copy link

rof20004 commented Nov 13, 2021

What about this solution guys?

package chapter01.exercise_18;

public class CheckTwoStringsAnagram {

    public static void main(String[] args) {
        var one = "geeksforgeeks";
        var two = "forgeeksgeeks";
        var areAnagrams = checkIfTwoStringsAreAnagrams(one, two);
        System.out.format("The strings \"%s\" and \"%s\" are anagrams? %b", one, two, areAnagrams);
    }

    private static boolean checkIfTwoStringsAreAnagrams(final String one, final String two) {
        var oneWithoutSpacesAndLowerCase = one.replaceAll("\\s", "").toLowerCase();
        var twoWithoutSpacesAndLowerCase = two.replaceAll("\\s", "").toLowerCase();
        var countOneCharacters = oneWithoutSpacesAndLowerCase.chars().sum();
        var countTwoCharacters = twoWithoutSpacesAndLowerCase.chars().sum();
        return !oneWithoutSpacesAndLowerCase.equals(twoWithoutSpacesAndLowerCase)
                && countOneCharacters == countTwoCharacters;
    }

}

@rof20004
Copy link

A much more simple solution:

private static boolean isAnagram(String a, String b) {
    if (a.length() != b.length()) {
        return false;
    }
    a = a.toLowerCase();
    b = b.toLowerCase();
    
    for (int i = 0; i < b.length(); i++) {
        a = a.replaceFirst(String.valueOf(b.charAt(i)), "");
    }

    return a.isEmpty() ? true : false;
}

Is more simple than everything 👯

@yagamilightkira
Copy link

yagamilightkira commented Dec 16, 2022

static boolean isAnagram(String a, String b) {
        // Complete the function
        a = a.toLowerCase();
        b = b.toLowerCase();
        int aVal = 0, bVal = 0;
        
        
        if ( a.length() != b.length() )
            return false;
        for ( int i = 0; i < a.length(); i++ ) {
            aVal += (int)a.charAt(i)*(int)a.charAt(i);
            bVal += (int)b.charAt(i)*(int)b.charAt(i);
        }
        
        return aVal == bVal ? true : false;
    }

seems this is more simpler...

@divyush001
Copy link

import java.util.Scanner;

public class Solution {

static boolean isAnagram(String a, String b) {
    // Complete the function
    if(a.length() == b.length()){
        
    
        a=a.toUpperCase();
        b=b.toUpperCase();
        char[] ch1 = a.toCharArray();
        char[] ch2 = b.toCharArray();
        char temp;
        for(int i=0;i<ch1.length;i++){
            for(int j=i+1;j<ch1.length;j++){
                if(ch1[i]>ch1[j]){
                    temp =  ch1[i];
                    ch1[i] =ch1[j];
                    ch1[j] = temp; 
                }
            }
        }
        for(int i=0;i<ch2.length;i++){
            for(int j=i+1;j<ch2.length;j++){
                if(ch2[i]>ch2[j]){
                    temp =  ch2[i];
                    ch2[i] =ch2[j];
                    ch2[j] = temp; 
                }
            }
        }
        //System.out.println(ch1);
        //System.out.println(ch2);
        
        //int[] charcounta = new int[ch1.length];
        for (int i = ch1.length - 1; i >= 0; i--)   
        {  
            if(ch1[i]!=ch2[i]){
                return false;
            }else{
                continue;
            }
            
        }  
        return true;
    }
    return false;
}

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    String a = scan.next();
    String b = scan.next();
    scan.close();
    boolean ret = isAnagram(a, b);
    System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment