zoukankan      html  css  js  c++  java
  • Leetcode 49.字母异位词分组

    字母异位词分组

    给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

    示例:

    输入: ["eat", "tea", "tan", "ate", "nat", "bat"],

    输出:

    [

    ["ate","eat","tea"],

    ["nat","tan"],

    ["bat"]

    ]

    说明:

    • 所有输入均为小写字母。
    • 不考虑答案输出的顺序。

    方法一:排序数组分类

    思路

    当且仅当它们的排序字符串相等时,两个字符串是字母异位词。

    算法

    维护一个映射 ans : {String -> List},其中每个键 K ext{K}K 是一个排序字符串,每个值是初始输入的字符串列表,排序后等于 K ext{K}K。

    在 Java 中,我们将键存储为字符串,例如,code。 在 Python 中,我们将键存储为散列化元组,例如,('c', 'o', 'd', 'e')。

     

     1 class Solution {
     2     public List<List<String>> groupAnagrams(String[] strs) {
     3         if (strs.length == 0) return new ArrayList();
     4         Map<String, List> ans = new HashMap<String, List>();
     5         for (String s : strs) {
     6             char[] ca = s.toCharArray();
     7             Arrays.sort(ca);
     8             String key = String.valueOf(ca);
     9             if (!ans.containsKey(key)) ans.put(key, new ArrayList());
    10             ans.get(key).add(s);
    11         }
    12         return new ArrayList(ans.values());
    13     }
    14 }

     

     

    方法二:按计数分类

    思路

    当且仅当它们的字符计数(每个字符的出现次数)相同时,两个字符串是字母异位词。

    算法

    我们可以将每个字符串 s ext{s}s 转换为字符数 count ext{count}count,由26个非负整数组成,表示 a ext{a}a,b ext{b}b,c ext{c}c 的数量等。我们使用这些计数作为哈希映射的基础。

    在 Java 中,我们的字符数 count 的散列化表示将是一个用 **#** 字符分隔的字符串。 例如,abbccc 将表示为 #1#2#3#0#0#0 ...#0,其中总共有26个条目。 在 python 中,表示将是一个计数的元组。 例如,abbccc 将表示为 (1,2,3,0,0,...,0),其中总共有 26 个条目。

     

     1 class Solution {
     2     public List<List<String>> groupAnagrams(String[] strs) {
     3         if (strs.length == 0) return new ArrayList();
     4         Map<String, List> ans = new HashMap<String, List>();
     5         int[] count = new int[26];
     6         for (String s : strs) {
     7             Arrays.fill(count, 0);
     8             for (char c : s.toCharArray()) count[c - 'a']++;
     9 
    10             StringBuilder sb = new StringBuilder("");
    11             for (int i = 0; i < 26; i++) {
    12                 sb.append('#');
    13                 sb.append(count[i]);
    14             }
    15             String key = sb.toString();
    16             if (!ans.containsKey(key)) ans.put(key, new ArrayList());
    17             ans.get(key).add(s);
    18         }
    19         return new ArrayList(ans.values());
    20     }
    21 }

     

     

  • 相关阅读:
    sqlalchemy 使用pymysql连接mysql 1366错误
    mysql之数据导出
    Go常见语句
    huffman code
    后缀数组,目前比较赶进度,而且有点难,所以放到以后再来看
    hash
    bipartite matching
    spanning tree
    拓扑排序
    Union Find
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10163027.html
Copyright © 2011-2022 走看看