leetcode-242 判断两个字符串是不是 Anagram ?
2024-08-24 00:26:12
题目描述
假设给定两个字符串 s 和 t, 让我们写出一个方法来判断这两个字符串是否是字母异位词?
字母异位词就是,两个字符串中含有字母的个数和数量都一样,比如:
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
字符串 s 和 t 含有的字母以及字母的数量都一致,所以是 True.
Example 2:
Input: s = "rat", t = "car"
Output: false
字符串 s 中字母 "t" 在字符串 t 中并未出现,所以是 False.
解题思路
1) 可以初始化一个 hash map,键作为出现的字母,值作为对应字母出现的次数。
2)然后遍历字符串 s,将 map 中对应出现的字母个数加一。
3)然后接着遍历字符串 t, 将 map 中对应出现的字母个数减一。
4)最后判断 map 中是否所有的值都为 0 就可以了,如果不为 0 的话,一定表示 s 和 t 中拥有不同的字母。
# Question:
# Given two strings s and t , write a function to determine if t is an
# anagram of s.
# Type: string or array
# Example 1:
# Input: s = "anagram", t = "nagaram"
# Output: true
# Example 2:
# Input: s = "rat", t = "car"
# Output: false
# Note:
# You may assume the string contains only lowercase alphabets.
# Follow up:
# What if the inputs contain unicode characters?
# How would you adapt your solution to such case?
import string
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# get all lower alphabets
lower_alphabets = string.ascii_lowercase
# we can init a hash map to represent the count of alphabets.
lower_alphabets_map = {alphabet: 0 for alphabet in lower_alphabets}
# Traverse the string "s" and plus 1 to the count of alphabet
# that appear
for index in s:
if index in lower_alphabets_map.keys():
lower_alphabets_map[index] += 1
# Then Traverse the string "t" and subtract 1 to the count of alphabet
# that appear
for index in t:
if index in lower_alphabets_map.keys():
lower_alphabets_map[index] -= 1
# if the count of all alphabets in the hash map is 0, then the string
# "s" and "t" are anagrams.
is_anagram = False
for value in lower_alphabets_map.values():
if value != 0:
return is_anagram
return True
if __name__ == '__main__':
solution = Solution()
print(solution.isAnagram('abc', 'abc'))
最新文章
- apk反编译工具
- Struts2文件上传与下载
- Inverted sentences
- java-EL
- 主题:Android、iPhone和Java三个平台一致的加密工具
- tomcat + apache +jkmod 配置php,jsp共存
- cannot access the system temp folder
- Central Europe Regional Contest 2012 Problem J: Conservation
- 巧用DISPLAY_AWR函数与dba_hist_sqlstat结合查询SQL语句在指定节点指定时间范围内的历史执行计划
- boost进程间通信经常使用开发一篇全(消息队列,共享内存,信号)
- 阿里云服务器windows系统C盘一键清理脚本
- vue-cli安装
- javaScript手记(01)
- for循环中按条件删除数据元素
- caffe中的卷积
- maven项目启动报错;class path resource [com/ssm/mapping/] cannot be resolved to URL because it does not exist
- maven-compiler-plugin升级到3.1出现问题(转)
- LeetCode--136--只出现一次的数字
- [转]Tornado get/post请求异步处理框架分析
- 约瑟夫环问题算法(M)
热门文章
- sql优化提速整理
- Python编程系列---使用字典实现路由静态路由
- chrome devtools tip(1)--调试伪类
- .NETCore下CI/CD之自动化测试
- solr学习篇(四) java使用solr简单查询(初识solrj)
- 品优购(IDEA版)-第一天
- SpringCloud之Hystrix断路器(六)
- vim配置(vimplus)教程及问题
- (转载)学校搭建使用nginx同时编译rtmp-module进行直播的技术文档
- [Hadoop]Hive-1.2.x安装配置+Mysql安装