patternjavaMinor
Determining if two strings are anagrams of each other
Viewed 0 times
determiningeachanagramsaretwootherstrings
Problem
Is this code a good solution for the question, or is there a better way to do it?
package ArraysAndStrings;
import java.util.Arrays;
public class anagram{
private boolean isAnagram = false;
public boolean Anagrams(String str1, String str2){
if(str1.length() != str2.length()){
return isAnagram;
}
boolean [] char_set = new boolean[256];
boolean [] char_set1 = new boolean [256];
for(int i =0;i<str1.length();i++){
int val1 = str1.charAt(i);
int val2 = str2.charAt(i);
char_set[val1] = true;
char_set1[val2] = true;
}
if(Arrays.equals(char_set, char_set1)){
isAnagram = true;
}
return isAnagram;
}
public static void main(String [] args){
anagram ang = new anagram();
System.out.println(ang.Anagrams("mary","army"));
}
}Solution
The code is technically broken: it only tells that the strings are composed of the same letters. It is not enough for the strings to be anagrams. Each letter must appear the same number of times in both strings.
Making your
Making your
char_set array integer instead of boolean you can get the correct result still in linear time:int [] counters = new int[256];
set_counters_to_zero();
for (int i = 0; i < str1.len(); i++) {
counters[str1.charAt(i)]++;
}
for (int i = 0; i < str2.len(); i++) {
counters[str2.charAt(i)]--;
}
return all_counters_are_zero();Code Snippets
int [] counters = new int[256];
set_counters_to_zero();
for (int i = 0; i < str1.len(); i++) {
counters[str1.charAt(i)]++;
}
for (int i = 0; i < str2.len(); i++) {
counters[str2.charAt(i)]--;
}
return all_counters_are_zero();Context
StackExchange Code Review Q#116918, answer score: 8
Revisions (0)
No revisions yet.