Question
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = “anagram”, t = “nagaram”
Output: true
Example 2:
Input: s = “rat”, t = “car”
Output: false
关键词:字符串
Solution
判断s和t是否包含相同的字符。
几个思路:
1)两个字符串从大到小排好序,挨个儿比较。O(N·log(N)) + O(1)
2)用另外两个dic储存每个字符串所有的字符及其个数,挨个儿比较。O(N) + O(2·N)
3)用一个dic记住字符串s(加法),然后遍历字符串t,重新操作dic(减法),如果s和t组成相同,那么dic最终全是0。由于字符是有限的,甚至我们不需要dic,用一个数组来代表字符(C++版本使用的技巧)。O(N) + O(N)。
就写一下第三个。
时间复杂度:O(N)
空间复杂度:O(N)
- Python
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
li = 'abcdefghijklmnopqrstuvwxyz'
dic = {}
for l in li:
dic[l] = 0
for ss in s:
dic[ss] += 1
for tt in t:
dic[tt] -= 1
for l in li:
if dic[l]!=0:
return False
return True
- C++
class Solution {
public:
bool isAnagram(string s, string t) {
int alp[26]={};
for (int i = 0; i < s.length(); i++)
alp[s.at(i) - 'a']++;
for (int i = 0; i < t.length(); i++)
alp[t.at(i) - 'a']--;
for (int i=0;i<26;i++)
if (alp[i] != 0)
return false;
return true;
}
};