HackerRank Java- Anagrams




Two strings, a and b, are called anagrams if they contain all the same characters in the same frequencies. For example, the anagrams of CAT are CAT, ACT, TAC, TCA, ATC, and CTA.

Complete the function in the editor. If a and b are case-insensitive anagrams, print "Anagrams"; otherwise, print "Not Anagrams" instead.



  1. import java.util.Scanner;
  2. public class Solution {
  3. static boolean isAnagram(String a, String b) {
  4. a=a.toUpperCase();
  5. b=b.toUpperCase();
  6. boolean ret = false;
  7. StringBuilder c= new StringBuilder(b);
  8. if(a.length()==b.length()){
  9. for(int i=0; i<a.length();i++){
  10. for(int j=0; j<c.length();j++){
  11. if(a.charAt(i)==c.charAt(j)){
  12. c.deleteCharAt(j);
  13. if(i==a.length()-1 && c.length()==0){
  14. ret=true;
  15. break;
  16. }
  17. break;
  18. }
  19. }
  20. }
  21. }return ret;
  22. }
  23. public static void main(String[] args) {
  24. Scanner scan = new Scanner(System.in);
  25. String a = scan.next();
  26. String b = scan.next();
  27. scan.close();
  28. boolean ret = isAnagram(a, b);
  29. System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
  30. }
  31. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube