本文主要是介绍【LeetCode】Anagrams,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
AnagramsTotal Accepted: 7632 Total Submissions: 33683 My Submissions
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
举例说明题目大意:
String strs[] = {"aba","aab","baa","abc","def","cba"};
返回的结果应该是{"aba","aab","baa","abc","cba"};
其实就是求给定的数组中,按照字符串排序后一样的所有的元素集合。
用Map记录每个排好序的字符在数组中第一次出现的位置,如果后续再循环,发现有出现过,那么就放入list中。
注意不要重复存入数据。
Java AC
public class Solution {public ArrayList<String> anagrams(String[] strs) {ArrayList<String> list = new ArrayList<String>();int len = strs.length;Map<String, Integer> wordMap = new HashMap<String, Integer>();int visit[] = new int[len];for(int i = 0; i < len; i++){char array[] = strs[i].toCharArray();Arrays.sort(array);String newStr = new String(array);if(wordMap.containsKey(newStr)){int index = wordMap.get(newStr);if(visit[index] == 0){list.add(strs[index]);visit[index] = 1;}list.add(strs[i]);}else{wordMap.put(newStr, i);}}return list;}
}
这篇关于【LeetCode】Anagrams的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!