-1

Can someone explain to me how the marked lines below work? What do they do exactly?

public class GrammerUtils {         

    public static void main(String args[]) {
        System.out.print(isAnagram("teacher", "cheater"));    
    }

    public static boolean isAnagram(String word, String anagram) {
        if (word.length() != anagram.length()) {
            return false;
        }  
        char[] chars = word.toCharArray(); // marked
        for (char c: chars) {              // marked
            int index = anagram.indexOf(c);// marked
            if (index != -1) {             // marked
                anagram = anagram.substring(0, index) + anagram.substring(index + 1, anagram.length());
            } else {
                return false;
            }
        }
        return anagram.isEmpty();
    }
}
martijnn2008
  • 3,552
  • 5
  • 30
  • 40
Namenone
  • 344
  • 2
  • 5
  • 19

7 Answers7

3

The code takes one character in the word after another

char[] chars = word.toCharArray();
for (char c: chars) {

and checks if it is in the potential anagram.

int index = anagram.indexOf(c);

If yes

if (index != -1) {

then removes it so that it is not checked again in case there are repetitions (you take the substring before the character and the substring after the character, keep in mind that substring is exclusive in the second parameter):

 anagram = anagram.substring(0, index) + anagram.substring(index + 1, anagram.length());

and goes to the next character (When you finish checking all characters in the word, you check if all the characters in the anagram were matched, i.e. if the anagram is now empty).

If the character is not in the anagram then it means it is not an anagram, and you return false.

 return false;

This is rather inefficient (O(n^2)). Better to sort both strings and compare the results (O(n*log(n))

Jirka
  • 4,184
  • 30
  • 40
1

i tried it the below way without using indexes

package com.learn.java.fileop;

public class Anagram {


        public boolean checkAnagram(String basestr , String anastr){

        char[] ch = basestr.toCharArray();
        char[] ch1 = anastr.toCharArray();

        int asciivalue=0;
        int sum_src=0;
        for(int i =0 ; i< ch.length;i++){
            asciivalue = ch[i];
            sum_src = sum_src+asciivalue;
        }
        System.out.println(""+sum_src);
        int sum_dest=0;
        for(int i = 0 ; i< ch1.length;i++){
            asciivalue = ch1[i];
            sum_dest = sum_dest+asciivalue;
         }

         System.out.println(""+sum_dest);
         if (sum_src == sum_dest){
             return true;
         }else{
             return false;
         }
}
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Anagram an = new Anagram();
    System.out.println(an.checkAnagram("teacher", "cheater"));
}

}

Please let me know if this looks ok or any other thoughts on this.

1

This doesn't answer your question, but is asymptotically a more efficient algorithm.

public static void isAnagram(String s1, String s2){
    char[] c1 = s1.toLowerCase().toCharArray();
    char[] c2 = s2.toLowerCase().toCharArray();

    Arrays.sort(c1);
    Arrays.sort(c2);

    if(Arrays.equals(c1, c2))
        System.out.println("s1 is anagram of s2");
    else
        System.out.println("Strings are not anagram");
}
martijnn2008
  • 3,552
  • 5
  • 30
  • 40
Nik's
  • 21
  • 4
0

The code loops through every character of word. For each character, it checks to see if its in anagram. If its not, it returns false. Otherwise, it removes the character from anagram and moves on to the next character.

public static boolean isAnagram(String word, String anagram) {
    if (word.length() != anagram.length()) {
        return false;
    }  
    char[] chars = word.toCharArray();
    //loop through each character in `word`
    for (char c: chars) {
      int index = anagram.indexOf(c);
        //if it exists in `anagram`, remove it using a combination of `substring` calls, else return false
        if (index != -1) {
          anagram = anagram.substring(0, index) + anagram.substring(index + 1, anagram.length());
        } else {
            return false;
        }
    }
    return anagram.isEmpty();
}
go-oleg
  • 19,272
  • 3
  • 43
  • 44
0

The code is rather inefficient also in the sense that it creates a new String in every step of the for loop, and reassign it to anagram. Below is a way using java.util.Arrays, which contains various utility methods for manipulating arrays. And last, isAnagarm() likely should be a static util method.

public static boolean isAnagram(String s, String t) {
    if (s == null || t == null) {
        return false;
    }

    if(s.isEmpty() && t.isEmpty()) {
        return true;
    }

    char[] sArray = s.toCharArray();
    char[] tArray = t.toCharArray();
    Arrays.sort(sArray);
    Arrays.sort(tArray);

    return Arrays.equals(sArray, tArray);
}
BJYC
  • 354
  • 2
  • 10
0
   Program to check the entered strings are Anagram:

   public class AnagramWordTest {
     public static void main(String[] args) {
     String str1 = "cat";
     String str2 = "tac";

    int not_found=0;
    if(str1.length() == str2.length()) {

        Boolean isDuplicate = 
   testDuplicatesinEachWord(str1.toLowerCase().trim(), 
     str2.toLowerCase().trim());

        if(!isDuplicate) {
            int found=0;
            for (int i = 0; i < str1.length(); i++) {
                for (int j = 0; j < str2.length(); j++) {


                    if(str1.charAt(i) == str2.charAt(j)) {
                        found=1;
                        break;
                    }
                }
                if(found == 0) {
                    not_found=1;
                    break;
                }
            }

            if(not_found==1) {
                System.out.println("The two strings are not Anagrams");
            }else {
                System.out.println("The two strings are Anagrams");

            }
        } else {
            System.out.println("Entered strings has duplicates to check 
            Anagrams in either");
        }

    }else {
        System.out.println("String lengths are different and are not 
         Anagram");
    }
   }

  private static boolean testDuplicatesinEachWord(String str1, String str2) 
  {
    Boolean isStr1Duplicate = false;
    Boolean isStr2Duplicate = false;
    Boolean isDuplicate = false;
    for(int k=0;k<str1.length();k++) {
        for(int m=k+1;m<str1.length()-1;m++) {
            if(str1.charAt(k) == str1.charAt(m)) {
                isStr1Duplicate = true;
                break;
            }
        }
    }

    for(int l=0;l<str2.length()-1;l++) {
        for(int n=l+1;n<str1.length()-1;n++) {
            if(str1.charAt(l) == str2.charAt(n)) {
                isStr2Duplicate = true;
                break;
            }}
    }

    if(isStr1Duplicate.equals(Boolean.TRUE) || 
        isStr2Duplicate.equals(Boolean.TRUE)) {
        isDuplicate= true;
    }
    return isDuplicate;
    }
  }
satish hiremath
  • 127
  • 1
  • 4
-1

// Importing the Arrays class that will help us manipulate arrays. import java.util.Arrays;

public class AnagramTest {

private static boolean isAnagram(String str1 , String str2){
        // Converting both strings to char arrays as strings do not have direct
        // sorting method in java.
        char [] leftArray = ( str1.trim().toLowerCase()).toCharArray();
        char [] rightArray = ( str2.trim().toLowerCase()).toCharArray();
        Arrays.parallelSort(leftArray); // Sorting the array using the java 8 
        Arrays.parallelSort(rightArray);// parallelSort method

        return Arrays.equals(leftArray, rightArray);
    }               
public static void main(String [] args){
        //Test cases;
        String a = "integral"; // initializing first string
        String b = "Triangle"; // initializing second string
        System.out.println("The statement "+ a + " is anagram of "+b+" is "+isAnagram(a,b));// Print true

        String c = "silent"; // initializing first string
        String d = "listen"; // initializing second string
        System.out.println("The statement "+ c + " is anagram of "+d+" is "+isAnagram(c,d));// Print true

        String e = "fried"; // initializing first string
        String f = "fired"; // initializing second string
        System.out.println("The statement "+ e + " is anagram of "+f+" is "+isAnagram(e,f));// true            
        String g = "ball"; // initializing first string
        String h = "call"; // initializing second string
        System.out.println("The statement "+ g + " is anagram of "+h+"is "+isAnagram(g,h));// Print false                       
    }           

}