TypechoJoeTheme

IT技术分享

统计

[LeetCode 49] Group Anagrams [Java]

2018-01-16
/
0 评论
/
714 阅读
/
正在检测是否收录...
01/16

1. Description

Given an array of strings, group anagrams together.

Note: All inputs will be in lower-case.

2. Example

given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]

3. Code

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LeetCode0049 {
    public List> groupAnagrams(String[] strs) {

        List> result = new ArrayList>();

        if (strs == null || strs.length == 0) {
            return result;
        }

        Map> map = new HashMap>();

        for (int i = 0; i < strs.length; i++) {
            String str = strs[i];
            char array[] = str.toCharArray();
            Arrays.sort(array);
            String hash = String.valueOf(array);
            if (map.containsKey(hash)) {
                map.get(hash).add(str);
            } else {
                map.put(hash, new ArrayList());
                map.get(hash).add(str);
            }
        }
        result.addAll(map.values());
        return result;
    }

    public static void main(String[] args) {
        LeetCode0049 leetcode = new LeetCode0049();
        List> result = leetcode.groupAnagrams(new String[] { "eat", "tea", "tan", "ate", "nat", "bat" });
        for (int i = 0; i < result.size(); i++) {
            for (int j = 0; j < result.get(i).size(); j++) {
                System.out.print(result.get(i).get(j) + " ");
            }
            System.out.println();
        }
    }
}
Map
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1386/(转载时请注明本文出处及文章链接)