Given two strings s and , 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

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?

给2个字符串s和t,写一个判断二者是否为变位词的函数。

解法1:利用HashMap记录s中出现的字母和数量,然后在用t的字母和数量来验证。

解法2:把两个string变为char array,对两个array进行排序,然后比较是否一样。

Java:

class Solution {
public boolean isAnagram(String s, String t) {
HashMap<Character, Integer> map = new HashMap<>(); // first time: store each s char and occurrence into map
for(int i=0; i<s.length(); i++) {
char sChar = s.charAt(i);
map.put(sChar, map.getOrDefault(sChar, 0) + 1);
}
// second time: compare t char with map to see match or not
for(int i=0; i<t.length(); i++) {
char tChar = t.charAt(i); if(!map.containsKey(tChar))
return false; if(map.get(tChar) == 1)
map.remove(tChar);
else
map.put(tChar, map.get(tChar) - 1); } return map.size() == 0 ? true : false;
}
} 

Java:

public class Solution {
public boolean isAnagram(String s, String t) {
int[] alphabet = new int[26];
for (int i = 0; i < s.length(); i++) alphabet[s.charAt(i) - 'a']++;
for (int i = 0; i < t.length(); i++) alphabet[t.charAt(i) - 'a']--;
for (int i : alphabet) if (i != 0) return false;
return true;
}
}  

Python:  T: O(n)  S: O(1)

class Solution:
def isAnagram(self, s, t):
if len(s) != len(t):
return False count = {} for c in s:
if c.lower() in count:
count[c.lower()] += 1
else:
count[c.lower()] = 1 for c in t:
if c.lower() in count:
count[c.lower()] -= 1
else:
count[c.lower()] = -1
if count[c.lower()] < 0:
return False return True

Python: wo

class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
a = [0] * 256
for i in s:
a[ord(i)] += 1 b = [0] * 256
for j in t:
b[ord(j)] += 1 return a == b   

Python:  T: O(n)  S: O(1)

class Solution:
def isAnagram3(self, s, t):
if len(s) != len(t):
return False
count = collections.defaultdict(int)
for c in s:
count[c] += 1
for c in t:
count[c] -= 1
if count[c] < 0:
return False
return True

Python:

def isAnagram1(self, s, t):
dic1, dic2 = {}, {}
for item in s:
dic1[item] = dic1.get(item, 0) + 1
for item in t:
dic2[item] = dic2.get(item, 0) + 1
return dic1 == dic2  

Python:  T: O(nlogn)  S: O(n)

class Solution:
def isAnagram(self, s, t):
return sorted(s) == sorted(t)

C++:

class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
int m[26] = {0};
for (int i = 0; i < s.size(); ++i) ++m[s[i] - 'a'];
for (int i = 0; i < t.size(); ++i) {
if (--m[t[i] - 'a'] < 0) return false;
}
return true;
}
};

    

All LeetCode Questions List 题目汇总

  

  

[LeetCode] 242. Valid Anagram 验证变位词的更多相关文章

  1. [leetcode]242. Valid Anagram验证变位词

    Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: ...

  2. [LeetCode] Valid Anagram 验证变位词

    Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = & ...

  3. 22. leetcode 242. Valid Anagram(由颠倒字母顺序而构成的字)

    22. 242. Valid Anagram(由颠倒字母顺序而构成的字) Given two strings s and t, write a function to determine if t i ...

  4. LN : leetcode 242 Valid Anagram

    lc 242 Valid Anagram 242 Valid Anagram Given two strings s and t, write a function to determine if t ...

  5. LeetCode 242. Valid Anagram (验证变位词)

    Given two strings s and t, write a function to determine if t is an anagram of s. For example,s = &q ...

  6. Leetcode 242. Valid Anagram(有效的变位词)

    Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = & ...

  7. LeetCode 242 Valid Anagram

    Problem: Given two strings s and t, write a function to determine if t is an anagram of s. For examp ...

  8. (easy)LeetCode 242.Valid Anagram

    Given two strings s and t, write a function to determine if t is an anagram of s. For example,s = &q ...

  9. Java [Leetcode 242]Valid Anagram

    题目描述: Given two strings s and t, write a function to determine if t is an anagram of s. For example, ...

随机推荐

  1. Spring源码窥探之:注解方式的AOP原理

    AOP入口代码分析 通过注解的方式来实现AOP1. @EnableAspectJAutoProxy通过@Import注解向容器中注入了AspectJAutoProxyRegistrar这个类,而它在容 ...

  2. LeetCode 449. Serialize and Deserialize BST

    原题链接在这里:https://leetcode.com/problems/serialize-and-deserialize-bst/description/ 题目: Serialization i ...

  3. solidworks 学习 (一)

    螺丝刀建模

  4. STATUS_STACK_BUFFER_OVERRUN不一定是栈缓冲区溢出

    STATUS_STACK_BUFFER_OVERRUN异常一般是指栈缓冲区溢出的溢出,代码为0xC0000409,消息提示一般为“Security check failure or stack buf ...

  5. 文件搜索命令find

    1.路径加文件名搜索(find): 查找的是etc目录下的以init为名字的文件. 加通配符后为模糊搜索,只要文件名中含有init即可. 查找etc目录下以init开头的七位文件名. 2.搜索时不区分 ...

  6. 使用terraform 生成自签名证书

    terraform 是一个很不错的基础设施工具,我们可以用来做关于基础设施部署的事情,可以实现基础设施即代码 以下演示一个简单的自签名证书的生成(使用tls provider) main.tf 文件 ...

  7. 03-树2 List Leaves (25 分)

    Given a tree, you are supposed to list all the leaves in the order of top down, and left to right. I ...

  8. mysql mod() 获取余数

    mysql> ,); +-----------+ | mod(,) | +-----------+ | | +-----------+ row in set (0.00 sec)

  9. zookeeper、hbase集成kerberos

    1.KDC创建principal 1.1.创建认证用户 登陆到kdc服务器,使用root或者可以使用root权限的普通用户操作: # kadmin.local -q “addprinc -randke ...

  10. django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applie

    Traceback (most recent call last): File "manage.py", line 15, in <module> execute_fr ...