Created
May 25, 2017 17:22
-
-
Save amilcar-andrade/0405d8b36479d79d9b9df878ec0f1537 to your computer and use it in GitHub Desktop.
Implementation of the isAnagram problem and groupAnagrams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
class Main { | |
public static void main(String[] args) { | |
List<String> words = new ArrayList<>(Arrays.asList("a", "b", "a", "d")); | |
List<List<String>> g = groupAnamgrams(words); | |
System.out.println(g); | |
} | |
public static List<List<String>> groupAnamgrams(List<String> anagrams){ | |
if (anagrams == null || anagrams.isEmpty()) { | |
return new ArrayList<List<String>>(); | |
} | |
Map<String, List<String>> map = new HashMap<>(); | |
for (String s : anagrams) { | |
String key = sort(s); | |
if (map.containsKey(key)) { | |
map.get(key).add(key); | |
} else { | |
List<String> listOfSameAnagrams = new ArrayList<String>(); | |
listOfSameAnagrams.add(key); | |
map.put(key, listOfSameAnagrams); | |
} | |
} | |
List<List<String>> groups = new ArrayList<>(); | |
for(Map.Entry<String, List<String>> entry : map.entrySet()) { | |
groups.add(entry.getValue()); | |
} | |
return groups; | |
} | |
public static boolean isAnagram(String s1, String s2) { | |
if (s1 == null && s2 == null) { | |
return true; | |
} | |
if (s1 == null && s2 != null) { | |
return false; | |
} | |
if (s2 == null && s1 != null) { | |
return false; | |
} | |
return sort(s1).equals(sort(s2)); | |
} | |
public static String sort(String unsortedString) { | |
char[] cha = unsortedString.toCharArray(); | |
// in place sorting | |
Arrays.sort(cha); | |
return new String(cha); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment