当前位置:网站首页>340-Leetcode 有效的字母异位词
340-Leetcode 有效的字母异位词
2022-04-21 23:22:00 【sp_13230409636】

方法一:排序
class Solution
{
public:
bool isAnagram(string s, string t)
{
int len1 = s.size();
int len2 = t.size();
if (len1 != len2)return false;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
int main()
{
Solution A;
cout << A.isAnagram("rat","car") << endl;
return 0;
}
时间复杂度:O(nlogn),其中 n 为 s 的长度。排序的时间复杂度为O(nlogn),比较两个字符串是否相等时间复杂度为 O(n),因此总体时间复杂度为 O(nlogn+n)=O(nlogn)
空间复杂度:O(logn)。排序需要 O(logn) 的空间复杂度。注意,在某些语言(比如 Java & JavaScript)中字符串是不可变的,因此我们需要额外的 O(n) 的空间来拷贝字符串。但是我们忽略这一复杂度分析,因为:
①这依赖于语言的细节;
②这取决于函数的设计方式,例如,可以将函数参数类型更改为 char[]。
方法二:哈希表
class Solution {
public:
bool isAnagram(string s, string t) {
int len1 = s.size();
int len2 = t.size();
if (len1 != len2)return false;
vector<int> table(26, 0);
for (auto& ch : s)
{
++table[ch - 'a'];
}
for (auto &ch : t)
{
if (--table[ch - 'a'] < 0)
{
return false;
}
}
return true;
}
};
时间复杂度:O(n),其中 n 为 s 的长度。
空间复杂度:O(S),其中 S 为字符集大小,此处 S=26
版权声明
本文为[sp_13230409636]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_45964837/article/details/124327554
边栏推荐
- Apache Flink series - ④ stateful functions
- How to set blind area in VOS
- Ruixin microchip AI part development record section 1 "PC side environment construction 2"
- 自定义模板问题求助,自动添加时间日期
- 【H.264】SPS 计算帧率方法
- Go language self-study series | golang pointer
- Tensorflow 2.8 installation
- [ffmpeg] command line
- The pattern should be large and the vision should be broad, and the humanitarian spirit should be upheld [continuous updating, do not delete]
- 【H.264】简单编码器及SPS
猜你喜欢

prompt 你到底行不行?

BUUCTF 你(竟)然赶我走

Vs2019 configuring opencv4

早晚安打卡签到v2.0.1 公众号模块

The three secret softwares of the leaders are practical and powerful, which are powerful tools for office efficiency and workplace promotion

第2章 MySQL数据库的安装

87 R k-means,层次聚类,EM聚类的实现

Basic concepts of audio and video and a simple introduction to ffmpeg

大厂面试必备技能,android音视频框架

IJCAI2022录用结果出炉!接收率15%,你中了吗?
随机推荐
MySQL problem solving_ Multi table joint query_ Please take out the corresponding data and output it in ascending order of accuracy.
大厂面试必备技能,android音视频框架
Amazing, 4 high-quality software full of surprises, feel more comfortable to use
Uni app image adaptation dynamic calculation of image height
Selection and evolution of microservices under cloud native architecture
瑞芯微芯片AI部分开发记录 第二节 《yolov3-tiny及darknet介绍》
How to set blind area in VOS
MySQL 第3章 SQL基础语法
Golang force buckle leetcode 2246 Longest path with different adjacent characters
Teach you to easily solve CSRF Cross Site Request Forgery Attack
早晚安打卡签到v2.0.1 公众号模块
Overloading of methods
File operation and IO
golang力扣leetcode 385.迷你语法分析器
[wrapper (1)]
格局要大与视野要广,秉持人道主义精神【持续更新中,勿删】
How to build an observable system that can "evolve continuously"| QCon
(10) RTSP video stream pulled by QT engineering ffmpeg in Ruixin micro rk3568
痞子衡嵌入式:聊聊系统看门狗WDOG1在i.MXRT1xxx系统启动中的应用及影响
VOS如何设置盲区