[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: 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 验证变位词的更多相关文章
- [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: ...
- [LeetCode] Valid Anagram 验证变位词
Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = & ...
- 22. leetcode 242. Valid Anagram(由颠倒字母顺序而构成的字)
22. 242. Valid Anagram(由颠倒字母顺序而构成的字) Given two strings s and t, write a function to determine if t i ...
- 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 ...
- 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 ...
- 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 = & ...
- 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 ...
- (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 ...
- 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, ...
随机推荐
- Python +urllib+urllib2 带数据的post请求实例
#coding:utf-8 ''' Created on 2017年11月2日 @author: li.liu ''' import urllib import urllib2 import re f ...
- Python常用标准库函数
math库: >>> import math >>> dir(math) ['__doc__', '__loader__', '__name__', '__pack ...
- 浏览器 Web Storage - sessionStorage & localStorage
storage事件 当储存的数据发生变化时,会触发storage事件.我们可以指定这个事件的回调函数. window.addEventListener("storage",onSt ...
- springboot 打成的jar包在ClassLoader().getResource方法读取文件为null
1.属性文件如下: 10001=错误 2.文件读取主要代码 // getResource方式 URL resourceURI = getClass().getClassLoader().getReso ...
- S1_搭建分布式OpenStack集群_06 nova服务配置 (控制节点)
一.创建数据库(控制节点)创建数据库以及用户:# mysql -uroot -p12345678MariaDB [(none)]> CREATE DATABASE nova_api;MariaD ...
- 洛谷P4047 [JSOI2010]部落划分题解
洛谷P4047 [JSOI2010]部落划分题解 题目描述 聪聪研究发现,荒岛野人总是过着群居的生活,但是,并不是整个荒岛上的所有野人都属于同一个部落,野人们总是拉帮结派形成属于自己的部落,不同的部落 ...
- Linux修改服务器Oracle字符集
Linux安装Oracle时太仓促,没设置好,导入dmp字符集(ZHS16GBK)与服务器字符集(WE8MSWIN1252)对不上,导致导入数据失败: [oracle@ORACLE ~]$ sqlpl ...
- Ajax.BeginForm 不执行OnSuccess
今天用MVC做了一个表单提交,使用Ajax.BeginForm ,但是碰到一个奇怪的问题OnSuccess回调函数不执行.后来经过多次尝试才发现要引用两个东西 1.<script src=&qu ...
- 【BZOJ4475】 [Jsoi2015]子集选取
题目描述 数据范围 \(1\leq N,K \leq 10^9\) \(solution\) 集合S中每个元素互不影响,不妨依次考虑其中一个元素在三角形中的出现情况 问题转化为一个\(0/1\)的三角 ...
- 微信小程序地图组件
index.wxml <map id="map" markers="{{markers}}" longitude="{{longitude}}& ...