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

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

2013.12.15 22:00

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

Note: All inputs will be in lower-case.

Solution:

  Anagrams means that strings composed of the same group of letters, such as [ate, eat, tea]. They'll become the same when sorted: aet.

  My solution is to sort every string, and sort the array according to the sorted form of each string element. Then group the strings together by anagrams.

  Time compexity is O(n * log(n)), where n is the length of the array. Space complexity is O(n).

Accepted code:

1 // 1CE, 1AC 2 #include 
3 #include
4 #include
5 using namespace std; 6 7 typedef struct st{ 8 public: 9 string str;10 string sorted_str;11 12 st(string _str = "", string _sorted_str = "") {13 str = _str;14 sorted_str = _sorted_str;15 }16 }st;17 18 bool comparator(const st &x, const st &y)19 {20 // 1CE here, return a.sorted_str < b.sorted_str;21 return x.sorted_str < y.sorted_str;22 }23 24 class Solution {25 public:26 vector
anagrams(vector
&strs) {27 // IMPORTANT: Please reset any member data you declared, as28 // the same Solution instance will be reused for each test case.29 int max_len = 0;30 int i, j, n;31 char *ps = nullptr;32 33 result.clear();34 v.clear();35 36 n = strs.size();37 if(n <= 0){38 return result;39 }40 for(i = 0; i < n; ++i){41 if(strs[i].length() > max_len){42 max_len = strs[i].length();43 }44 }45 ps = new char[max_len + 1];46 47 string s, ss;48 for(i = 0; i < n; ++i){49 s = strs[i];50 strcpy(ps, s.data());51 sort(ps, ps + s.length());52 ss = string(ps);53 v.push_back(st(s, ss));54 }55 sort(v.begin(), v.end(), comparator);56 delete[] ps;57 i = 0;58 while(i < n){59 j = i;60 while(j < n && v[i].sorted_str == v[j].sorted_str){61 ++j;62 }63 if(j - i > 1){64 while(i < j){65 result.push_back(v[i].str);66 ++i;67 }68 }69 i = j;70 }71 v.clear();72 73 return result;74 }75 private:76 vector
v;77 vector
result;78 };

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3475842.html

你可能感兴趣的文章
luogu1373 小a和uim之大逃离 (dp)
查看>>
Redis的Pub/Sub客户端实现
查看>>
SQL日常问题和技巧——持续更新
查看>>
springMVC入门(一)------springMVC基本概念与安装
查看>>
Sam做题记录
查看>>
[bzoj] 2453 维护数列 || 单点修改分块
查看>>
IIS版本变迁
查看>>
BZOJ3884: 上帝与集合的正确用法 拓展欧拉定理
查看>>
mybatis09--自连接一对多查询
查看>>
myeclipse10添加jQuery自动提示的方法
查看>>
【eclipse jar包】在编写java代码时,为方便编程,常常会引用别人已经实现的方法,通常会封装成jar包,我们在编写时,只需引入到Eclipse中即可。...
查看>>
视频监控 封装[PlayCtrl.dll]的API
查看>>
软件工程APP进度更新
查看>>
Python 使用正则替换 re.sub
查看>>
CTF中那些脑洞大开的编码和加密
查看>>
简化工作流程 10款必备的HTML5开发工具
查看>>
c++ 调用外部程序exe-ShellExecuteEx
查看>>
Java进击C#——语法之知识点的改进
查看>>
IdentityServer流程图与相关术语
查看>>
BirdNet: a 3D Object Detection Framework from LiDAR information
查看>>