当前位置:网站首页>力扣.有效的字母异位词
力扣.有效的字母异位词
2022-07-31 05:17:00 【旺仔 小馒头】
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
思路
法一 :暴力的解法,两层for循环,同时还要记录字符是否重复出现,很明显时间复杂度是 O(n^2)。
法二:数组其实就是一个简单哈希表,而且这道题目中字符串只有小写字符,那么就可以定义一个数组,来记录字符串s里字符出现的次数。
因为字符a到字符z的ASCII也是26个连续的数值。所以不需要定义过大的数组,只要让遍历的每一个字符的ASCII码值减去a对应ASCII值即可,它们的结果仍然是26个连续的值,所以数组大小26即可
先遍历第一个串s,记录s串中每一个字符出现的次数,然后再遍历字符串t,将t中每一个出现的串,如果这个字符也是s中出现过得,就让对应的hash值减1,当最后全部遍历完后,判断hash数组中的所有元素是否全为0,如果是说明是异位词,不全为0,则不是。
代码如下:
class Solution {
public:
bool isAnagram(string s, string t) {
//需要把字符映射到数组也就是哈希表的索引下标上,因为字符a到字符z的ASCII是26个连续的数值,所以字符a映射为下标0,相应的字符z映射为下标25。
int hash_map[26] = {0};
for (auto ch : s){
hash_map[ch - 'a']++;
}
for (auto ch : t){
hash_map[ch - 'a']--;
}
for (auto e : hash_map){
if(e!=0)
return false;
}
return true;
}
};相关题目:
边栏推荐
- DSPE-PEG-COOH CAS: 1403744-37-5 Phospholipid-polyethylene glycol-carboxy lipid PEG conjugate
- ROS之service传输图片
- crontab的定时操作
- 2021-09-30
- Redis-哈希
- DSPE-PEG-Thiol DSPE-PEG-SH 磷脂-聚乙二醇-巯基脂质体制备用
- Cholesterol-PEG-Thiol CLS-PEG-SH 胆固醇-聚乙二醇-巯基
- 计算图像数据集均值和方差
- Cholesterol-PEG-Amine CLS-PEG-NH2 Cholesterol-Polyethylene Glycol-Amino Research Use
- 概率论相关笔记
猜你喜欢

DingTalk Enterprise Internal-H5 Micro Application Development

Learning and understanding of ROS service programming

MySQL 免安装版的下载与配置教程

DSPE-PEG-Biotin,CAS:385437-57-0,磷脂-聚乙二醇-生物素可延长循环半衰期

DSPE-PEG-Azide DSPE-PED-N3 Phospholipid-Polyethylene Glycol-Azide Lipid PFG

Learn how to get a database connection with JDBC

Cholesterol-PEG-Amine CLS-PEG-NH2 Cholesterol-Polyethylene Glycol-Amino Research Use

【Rhapsody学习笔记】4:Relations

Picture-in-Picture API in the browser

Attention based ASR(LAS)
随机推荐
CAS:474922-22-0 Maleimide-PEG-DSPE Phospholipid-Polyethylene Glycol-Maleimide Brief Description
MW: 3400 4-Arm PEG-DSPE four-arm-polyethylene glycol-phospholipid a saturated 18-carbon phospholipid
MW:3400 4-Arm PEG-DSPE 四臂-聚乙二醇-磷脂一种饱和的18碳磷脂
虚拟机查看端口号进程
化学试剂磷脂-聚乙二醇-氨基,DSPE-PEG-amine,CAS:474922-26-4
MySQL 主从切换步骤
ROS subscription to multiple topics time synchronization problem
用pytorch里的children方法自定义网络
wangeditor富文本编辑器上传图片以及跨域问题解决
pytorch模型微调finetuning训练image_dog(kaggle)
The solution to the IDEA console not being able to enter information
[已解决]ssh连接报:Bad owner or permissions on C:\\Users/XXX/.ssh/config
Rejection sampling note
mPEG-DSPE 178744-28-0 Methoxy-polyethylene glycol-phosphatidylethanolamine linear PEG phospholipids
科研试剂Cholesterol-PEG-Maleimide,CLS-PEG-MAL,胆固醇-聚乙二醇-马来酰亚胺
深度学习知识点杂谈
Data Preprocessing, Feature Engineering, and Feature Learning - Excerpt
Numpy常用函数
Cholesterol-PEG-Thiol CLS-PEG-SH Cholesterol-Polyethylene Glycol-Sulfhydryl
关于Iframe