博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Valid Anagram (简单题)
阅读量:4325 次
发布时间:2019-06-06

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

 

 

题意:

  给出两个字符串s和t,判断串t是否为s打乱后的串。

 

 

思路:

  如果返回的是true,则两个串的长度必定相等,所有字符出现的次数一样。那么可以统计26个字母的次数来解决,复杂度O(n)。也可以排序后逐个比对,复杂度O(nlogn)。

 

 

 

 

第一种方法:

1 class Solution { 2 public: 3     bool isAnagram(string s,string t) 4     { 5         if(s.size()!=t.size())    return false; 6         int cnt[26][2]={
0}; 7 for(int i=0; i
AC代码

 

1 class Solution { 2 public: 3     bool isAnagram(string s,string t) 4     { 5         if(s.size()!=t.size())    return false; 6         int cnt[26]={
0}; 7 for(int i=0; i
AC代码

 

 

 

第二种方法:

1 class Solution { 2 public: 3     bool isAnagram(string s,string t) 4     { 5         if(s.size()!=t.size())    return false; 6         sort(s.begin(),s.end()); 7         sort(t.begin(),t.end()); 8         for(int i=0; i
AC代码

 

1 bool isAnagram(string s,string t)2 {3     sort(s.begin(),s.end());4     sort(t.begin(),t.end());    5     return s==t;6 }
AC代码

 

 

python3

1 class Solution(object): 2     def isAnagram(self, s, t): 3         """ 4         :type s: str 5         :type t: str 6         ::rtype: bool 7         """ 8         listt=list(t) 9         for x in s:10             try:11                 listt.remove(x)12             except ValueError:13                 return False14         return True if listt==[] else False
AC代码

 

1 class Solution(object): 2     def isAnagram(self, s, t): 3         """ 4         :type s: str 5         :type t: str 6         ::rtype: bool 7         """ 8         dic1, dic2= {}, {} 9         for x in s:10             dic1[x]=dic1.get(x,0)+111         for x in t:12             dic2[x]=dic2.get(x,0)+113         return dic1==dic2
AC代码

 

1 class Solution(object): 2     def isAnagram(self, s, t): 3         """ 4         :type s: str 5         :type t: str 6         ::rtype: bool 7         """ 8         cnt1, cnt2= [0]*26, [0]*26 9         for x in s:10             cnt1[ord(x)-ord('a')]+=111         for x in t:12              cnt2[ord(x)-ord('a')]+=113         return cnt1==cnt2
AC代码

 

1 class Solution(object):2     def isAnagram(self, s, t):3         """4         :type s: str5         :type t: str6         ::rtype: bool7         """8         return sorted(s)==sorted(t)
AC代码

 

转载于:https://www.cnblogs.com/xcw0754/p/4918769.html

你可能感兴趣的文章
Spring - DI
查看>>
微软自己的官网介绍 SSL 参数相关
查看>>
Composite UI Application Block (CAB) 概念和术语
查看>>
64位MATLAB和C混合编程以及联合调试
查看>>
原生js大总结二
查看>>
PHP基础
查看>>
UVa 11488 超级前缀集合(Trie的应用)
查看>>
Django 翻译与 LANGUAGE_CODE
查看>>
[转]iOS教程:SQLite的创建数据库,表,插入查看数据
查看>>
【转载】OmniGraffle (一)从工具栏开始
查看>>
初识ionic
查看>>
java 中打印调用栈
查看>>
开发 笔记
查看>>
数据挖掘算法比赛 - 简单经验总结
查看>>
生成商户订单号/退款单号
查看>>
使用Android OpenGL ES 2.0绘图之六:响应触摸事件
查看>>
我们过去几年做对了哪些事
查看>>
ubuntu 16.04LTS
查看>>
javascript深入理解js闭包
查看>>
Java Bigdecimal使用
查看>>