【Lintcode】171. Anagrams

题目地址:

https://www.lintcode.com/problem/anagrams/description

给定一个字符串组成的数组,返回其中所有的anagram。anagram意思是含有相同字母并且每个字母出现相同次数。

可以用一个哈希表,key是字符串,value是字符串组成的list,每个字符串内部字符都进行排序,排序后得到的字符串作为key,这样key一样的字符串就属于同一个anagram,这样就可以将anagram加到同一个list里,最后累计返回即可。下面如下:

import java.util.*;

public class Solution {
    /**
     * @param strs: A list of strings
     * @return: A list of strings
     */
    public List<String> anagrams(String[] strs) {
        // write your code here
        List<String> res = new ArrayList<>();
        if (strs == null || strs.length == 0) {
            return res;
        }
    
        Map<String, List<String>> map = new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
        	// 算每个anagram对应的唯一的key
            char[] s = strs[i].toCharArray();
            Arrays.sort(s);
            String key = new String(s);
            
            map.putIfAbsent(key, new ArrayList<>());
            map.get(key).add(strs[i]);
        }
    
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            if (entry.getValue().size() > 1) {
                res.addAll(entry.getValue());
            }
        }
        
        return res;
    }
}

时间复杂度 O ( n l log ⁡ l ) O(nl\log l) O(nllogl) n n n为字符串个数, l l l为最长字符串长度,空间 O ( n l ) O(nl) O(nl)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值