要求:
Please use javascript (or your favorite programming language) to write a
function that do the following.
Given an array of strings, return an array of arrays of strings that
groups all anagrams.
An anagram is a word that has the same letters, but in different positions.
i.e. given ["cars", "thing", "scar", "dog", "god", "arcs", "the"]
return [["cars", "scar", "arcs"], ["thing"], ["dog", "god"], ["the"]]
大体意思就是:用你熟悉的语言,将上面给出的数据 分成 下面的样子。
给出的单词可以是其他的单词。
思路: 既然是相同单词的不同位置,那么里面所含有的字母应该是一样的。所以想到将已有单词进行先排序(可以是从A-Z),
然后单词相同的为同一组的元素。
废话不多说 看代码:
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; /** * * @author guannan * */ public class TestPr { static HashMap<String, ArrayList<String>> strArr = new HashMap<String, ArrayList<String>>(); public static void main(String[] args) { ArrayList<String> ar = new ArrayList<String>(); // 添加要处理的数组 ar.add("cars"); ar.add("thing"); ar.add("scar"); ar.add("dog"); ar.add("god"); ar.add("arcs"); ar.add("the"); //排序活的要得到分组集合 syoArr(ar); //打印集合元素 showArr(strArr); } private static void showArr(HashMap<String, ArrayList<String>> strArr2) { //方法一:加强for // for (Map.Entry<String, ArrayList<String>> entry : strArr2.entrySet()) { // System.out.println("key :" + entry.getKey()); // for (int i = 0; i < entry.getValue().size(); i++) { // System.out.println(entry.getValue().get(i)); // } // } //方法二:普通遍历 Iterator i = strArr2.entrySet().iterator(); while(i.hasNext()){ Entry entry=(Entry)i.next(); System.out.println("key :" + entry.getKey()); ArrayList<String> value = (ArrayList<String>) entry.getValue(); for (int k = 0; k <value.size(); k++) { System.out.println(value.get(k)); } } } public static void syoArr(ArrayList<String> arr) { ArrayList<String> ar2 = new ArrayList<String>(); HashMap<String, String> ha = new HashMap<String, String>(); for (int i = 0; i < arr.size(); i++) { String stringByOrder = getStringByOrder(arr.get(i).toCharArray()); if (ha.containsKey(stringByOrder)) { ArrayList<String> arrayList = strArr.get(stringByOrder); arrayList.add(arr.get(i)); strArr.put(stringByOrder, arrayList); } else { ha.put(stringByOrder, arr.get(i)); ArrayList<String> ar1 = new ArrayList<String>(); ar1.add(arr.get(i)); strArr.put(stringByOrder, ar1); } } } public static String getStringByOrder(char[] oldChar) { Arrays.sort(oldChar); return String.valueOf(oldChar); } }
最后的输出结果:
key :eht
the
key :ghint
thing
key :dgo
dog
god
key :acrs
cars
scar
arcs
==========================================
一些小的技巧 献丑献丑
时间: 2024-10-14 08:26:31