Anagrams
Given an array of strings, return all groups of strings that are anagrams.
All inputs will be in lower-caseHave you met this question in a real interview? Yes
Example
Given ["lint", "intl", "inlt", "code"]
, return ["lint", "inlt", "intl"]
.
Given ["ab", "ba", "cd", "dc", "e"]
, return ["ab", "ba", "cd", "dc"]
.
Challenge
What is Anagram?
Two strings are anagram if they can be the same after change the order of characters.
public class Solution {
/**
* @param strs: A list of strings
* @return: A list of strings
*/
public List<String> anagrams(String[] strs) {
// write your code here
List<String> res = new ArrayList<>();
if(strs.length == 0 || strs == null) return res;
HashMap<String, ArrayList<String>> map = new HashMap<>();
for (int i = 0; i < strs.length ;i++ ){
char[] c = strs[i].toCharArray();
Arrays.sort(c);
String s = String.valueOf(c);
if(!map.containsKey(s)){
ArrayList<String> list = new ArrayList<>();
map.put(s,list);
}
map.get(s).add(strs[i]);
}
//Map.Entry<String, ArrayList<String>> entry : map.entrySet()
for(Map.Entry<String,ArrayList<String>> entry : map.entrySet()){
if(entry.getValue().size() >= 2){
res.addAll(entry.getValue());
}
}
return res;
}
}
Last updated