博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Anagrams
阅读量:4677 次
发布时间:2019-06-09

本文共 2525 字,大约阅读时间需要 8 分钟。

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

 

Solution and Precautions:

First, note what is Anagrams, you can google search it and let’s claim that word A and B is called anagram to each other if we can get word B(A) from A(B)  by rearranging the letters of A(B) to produce B(A), using all the original letters exactly once.

Then, one straightforward way is to compare each pair of words and to see if they are anagrams, my first try is just like this, starting from the first word, I search through all the remaining words and get its corresponding anagrams (to the first word), of course, all such anagrams we found for the first word won’t be anagrams to any other words so we don’t have to consider them for further check. This method could pass the small data set test but will get TLE for large dataset test. The time complexity is O(N^2 * K log K) where N is the number of words and K is the length of the longest word, or you may say the average length of the words.

Finally, if we think deeper into this, we will find that we actually don’t have to do the N^2 comparisons at all. The key observation is that A and B is anagram to each other if and only if their sorted form are exactly the same. As a result, one linear scan through the words list is enough, for each word we can get its sorted form in K log K time, and we can use map to store the groups of words which are in the same sorted form. The time complexity is O(N K log K), this approach could pass both small data test and large data test.

 

1 public class Solution { 2     public ArrayList
anagrams(String[] strs) { 3 // Note: The Solution object is instantiated only once and is reused by each test case. 4 int len = strs.length; 5 ArrayList
result = new ArrayList
(); 6 HashMap
> map = new HashMap
>(); 7 for(int i = 0; i < strs.length; i ++){ 8 char[] cs = strs[i].toCharArray(); 9 Arrays.sort(cs);10 String tmp = String.valueOf(cs);11 if(!map.containsKey(tmp)) map.put(tmp, new ArrayList
());12 map.get(tmp).add(strs[i]);13 }14 Iterator iter = map.values().iterator();15 while(iter.hasNext()){16 ArrayList
list = (ArrayList
)iter.next();17 if(list.size() > 1){18 result.addAll(list);19 }20 }21 return result;22 }23 }

 

转载于:https://www.cnblogs.com/reynold-lei/p/3412295.html

你可能感兴趣的文章
解决Admob Banner首次展示不显示的问题
查看>>
日志配置
查看>>
第四周作业 简单地邮件发送实现
查看>>
[转载]读史记札记26:容人岂皆有雅量
查看>>
【Xilinx-Petalinux学习】-02-建立PetaLinux工程
查看>>
TeX中的引号
查看>>
Python 模块(module)
查看>>
region实现大纲效果
查看>>
[洛谷P4234]最小差值生成树
查看>>
LiveNVR传统安防摄像机互联网直播-二次开发相关的API接口
查看>>
LiveNVR高性能稳定RTSP、Onvif探测流媒体服务配置通道接入海康、大华等摄像机进行全终端无插件直播...
查看>>
c c++ sizeof
查看>>
Intellij IDEA连接Spark集群
查看>>
最长回文子串解法
查看>>
代码优化程序性能
查看>>
腾讯实习生招聘笔试题目
查看>>
Java Socket编程----通信是这样炼成的
查看>>
作业要求 20180925-1 每周例行报告
查看>>
1078. Hashing (25)-PAT甲级真题
查看>>
SQLite中的运算符表达式
查看>>