Not a member of GistPad yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- List<List<String>> result = new ArrayList<>();
- // iterating over each string from giver array of strings
- {
- // convert the current string to charArray, and store hash values
- // suppose str is : "cat"
- int[] count = new int[26];
- for(char ch : str.toCharArray())
- {
- count[ch - 'a']++;
- }
- // count[0]=1 --> for 'a', count[2]=1 --> for 'c', count[19]=1 --> for 't'
- // convert count array into string
- StringBuilder sb = new StringBuilder();
- for(int index : count)
- {
- // adding hashes in between the count of characters
- sb.append("#").append(index);
- }
- // sb: "#1#0#1#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#1#0#0#0#0#0#0"
- // convert string builder to string
- // key = "#1#0#1#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#1#0#0#0#0#0#0"
- if(!map.containsKey(key))
- map.put(key, new ArrayList<String>());
- // Always add the string to the list, whether the key is new or not.
- // so suppose this key : {cat, act}, adding current string as anagram
- map.get(key).add(str);
- }
- result.addAll(map.values());
- return result;
- }
- }
RAW Paste Data
Copied
