We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Sherlock and Anagrams
Sherlock and Anagrams
Sort by
recency
|
1701 Discussions
|
Please Login in order to post a comment
My Java 8 solution, which passes all test cases, with max score = 50:
The basic idea is as follows:
(1) Iterate through the entire string once, and for each new / distinct character encountered, accumulate the List of Indices where the character occurs into
LinkedHashMap<Character, List<Integer>> chIdxMap
.(2) Iterate through all the Character Keys in
LinkedHashMap<Character, List<Integer>> chIdxMap
, and for each character: the Number of "Single Character Anagrams" (i.e. "aaa", "bbbb", etc) = (n * (n - 1)) / 2, where 'n' is the number of occurences of the character in the string.(3) Iterate through the string again, and for each Character at each Index, start from "Anagram Length = 2", and search for all Anagrams of that Length. And keep incrementing Anagram Length by 1 at each iteration.
(Ignore the verbose debug print statements. Those were added to test the logic before submission, and have been commented out once solution was finalized & verified that everything passed).
import java.io.; import java.util.;
class Result {
}
public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
}
Ruby solution:
A short CPP version:
Here's the approch that I implement to solve this problem with Kotlin: