You are not logged in. Please login at www.codechef.com to post your questions!

×

Grouping anagrams of strings together?

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<String> {
        @Override
        public int compare(String s1, String s2) {
            if (isAnaGram(s1, s2)) {
                return 0;
            }
            return s1.compareTo(s2);
        }
    }
}

asked 19 Oct '18, 12:22

arpit728's gravatar image

1★arpit728
6831563
accept rate: 10%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • 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