×

# Grouping anagrams of strings together?

 0 Given one array of strings, you have to sort the array such that anagrams should occur together. Below is my solution, can anyone tell me why this approach is not giving the correct answer.  class Solution { public static void main(String[] args) { String s[] = new String[]{"abc", "arp", "bac", "cba", "pra", "apr"}; Arrays.sort(s, new AnagramComparator()); System.out.println(Arrays.toString(s)); } private static boolean isAnaGram(String s1, String s2) { int freq[] = new int[26]; s1.chars().forEach(x -> freq[x - 'a']++); s2.chars().forEach(x -> freq[x - 'a']--); return Arrays .stream(freq) .allMatch(x -> x == 0); } static class AnagramComparator implements Comparator { @Override public int compare(String s1, String s2) { if (isAnaGram(s1, s2)) { return 0; } return s1.compareTo(s2); } } }  asked 19 Oct '18, 12:22 1★arpit728 683●15●63 accept rate: 10%
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×775
×630

question asked: 19 Oct '18, 12:22

question was seen: 32 times

last updated: 19 Oct '18, 12:22