anagram

An anagram is a new word or phrase formed by changing the alphabetical order of individual words or phrases, for example "triangle" is an anagram of "integral". The problem to be solved today is to write a method that sorts an array of strings so that all anagrams are placed next to each other.
Analysis:
Since anagrams are only different character sequences of different strings, a relatively simple idea is to sort the internal characters of all strings. If two strings are anagrams of each other, they will be the same after sorting. One way is to count the number of occurrences of each character in each string, and anagrams each other if they are the same. If it is not sorted, it can be solved by using a hash table. First, we use the sorted string as the key, all its anagrams as the values, group the anagrams together, and then output it to the array.
Java implementation (although not as concise as python, you can practice the basic data structure of java by the way)

package com.company;
import java.util.Hashtable;
import java.util.LinkedList;

public class GroupBianwei {
    public static ArrayList<String> sortf(String[] array){
        //String[] ar=new String[100];
        ArrayList<String>  strArray = new ArrayList<String> ();
        Hashtable<String,LinkedList<String>> hash=
        new Hashtable<String,LinkedList<String>>();
        for(String s:array){
            String key=sortChars(s);
        if(!hash.containsKey(key)){
            hash.put(key,new LinkedList<String>());
        }
        LinkedList<String> anagrams=hash.get(key);
        anagrams.push(s);
        }
        //int index=0;
        for(String key:hash.keySet()){
            LinkedList<String> list=hash.get(key);
            for(String t:list){
                //ar[index]=t;
                //index++;
                strArray.add(t);
            }
        }
        return strArray;
    }
    public static String sortChars(String str){
        char[] a=str.toCharArray();
        Arrays.sort(a);
        String rs = new String(a);
        return rs;
    }
    public static void main(String[] args) {
        String[] arr = {"acv","avc","fdd","dfd"};
        ArrayList<String> res = sortf(arr);
        System.out.println("the result is "+res);
    }
}

The output is:

the result is [dfd, fdd, avc, acv]

python implementation:

def group_anagrams(arr):
    dic = {}
    for a in arr:
        lis = []
        lis.append(a)
        key = ''.join(sorted(a))
        if key in dic.keys():
            lis.append(a)   
        dic[key]=lis
    for s in dic.values():
        print(s)

The output is:

['avc', 'avc']
['dfd', 'dfd']

Title from: "Cracking the Coding Interview (5th)"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325936019&siteId=291194637