今天两个easy的题目,目前希望把easy的难度做到看完题就立即有思路后,在进一步做medium的题目。
1. Jewels and Stones
1.1 问题描述
给定J代表是珠宝的石头,S代表你所拥有的石头。在S中的每一个字符代表你所拥有的石头的种类,你想要知道你有多少石头是属于珠宝的石头。
Input: J="aA", S="aAAbbbb"
Output: 3
1.2 解法&思路
1.2.1 暴力解法
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
count = 0
for j in J:
for s in S:
if s == j:
count = count + 1
return count
暴力解法,双层循环,时间复杂度:
(其中,m=length(J), n=length(S))
1.2.2 引入Dict,空间换时间
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
count = 0
Dict = {}
for s in S:
if s not in Dict:
Dict[s] = 1
else:
Dict[s] = Dict[s] + 1
for j in J:
if j in Dict:
count = count + Dict[j]
return count
利用字典统计一下字符的频率,时间复杂度为,空间复杂度。
(其中,m=length(J), n=length(S))
1.2.3 巧妙利用生成器
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
setJ = set(J)
return sum(s in setJ for s in S)
其中 (s in setJ for s in S)
是一个生成器,欧安段在
2. Unique Email Addresses
2.1 问题描述
一个邮件地址可以分为Localaddress和restaddress, 其中,@前的字符串称作localaddress, @后的字符串称作restaddress, 在Localaddress中,+后的字符忽略不计,“.”需要忽略不计。输入一个邮件地址的数组,经过以上条件进行筛选后,计算出一共几个不同的Email地址?
2.2 解法&思路
由于python中字符串是不可变的,故此本次利用JAVA解题,思路是利用上述规则进行模拟,将处理后的字符串放到集合里面,最后统计集合的元素个数即可。
class Solution {
public int numUniqueEmails(String[] emails) {
Set<String> str_set = new HashSet<>();
String replacement = "";
for (int i = 0; i < emails.length; i++) {
String toBeReplaced = emails[i].substring(emails[i].indexOf("+"), emails[i].indexOf("@"));
emails[i] = emails[i].replace(toBeReplaced, replacement);
toBeReplaced = emails[i].substring(0, emails[i].indexOf("@") - 1);
String final_replacement = toBeReplaced.replace(".", "");
emails[i] = emails[i].replace(toBeReplaced, final_replacement);
str_set.add(emails[i]);
}
return str_set.size();
}
leetcode的网站标准答案:
class Solution {
public int numUniqueEmails(String[] emails) {
Set<String> seen = new HashSet();
for (String email: emails) {
int i = email.indexOf('@');
String local = email.substring(0, i);
String rest = email.substring(i);
if (local.contains("+")) {
local = local.substring(0, local.indexOf('+'));
}
local = local.replaceAll(".", "");
seen.add(local + rest);
}
return seen.size();
}
}
最后还是发现了Python的解法,原来是用split和slice对local_address和domain两个字符串进行重新构造,代码如下:
class Solution(object):
def numUniqueEmails(self, emails):
seen = set()
for email in emails:
local, domain = email.split('@')
if '+' in local:
local = local[:local.index('+')]
seen.add(local.replace('.','') + '@' + domain)
return len(seen)
完毕,晚安。
网友评论