Skip to content

Commit

Permalink
AnagramTest - groupAnagrams
Browse files Browse the repository at this point in the history
  • Loading branch information
bky373 committed Jun 6, 2024
1 parent 0d7ad2f commit 7de9843
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/test/java/AnagramTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import static org.assertj.core.api.Assertions.assertThat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;

public class AnagramTest {

/**
* https://leetcode.com/problems/group-anagrams/
*/
@Test
void groupAnagrams() {
String[] strs = new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
Map<String, List<String>> groups = new HashMap<>();

for (String str : strs) {
char[] arr = str.toCharArray();
Arrays.sort(arr);
groups.computeIfAbsent(new String(arr), k -> new ArrayList<>())
.add(str);
}
List<List<String>> values = new ArrayList<>(groups.values());
assertThat(values).containsExactlyInAnyOrderElementsOf(List.of(
List.of("bat"),
List.of("tan", "nat"),
List.of("eat", "tea", "ate")
));
}
}

0 comments on commit 7de9843

Please sign in to comment.