今天兩個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
暴力解法,雙層循環(huán),時間復雜度:
(其中,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
利用字典統(tǒng)計一下字符的頻率,時間復雜度為,空間復雜度
。
(其中,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中,+后的字符忽略不計,“.”需要忽略不計。輸入一個郵件地址的數(shù)組,經(jīng)過以上條件進行篩選后,計算出一共幾個不同的Email地址?
2.2 解法&思路
由于python中字符串是不可變的,故此本次利用JAVA解題,思路是利用上述規(guī)則進行模擬,將處理后的字符串放到集合里面,最后統(tǒng)計集合的元素個數(shù)即可。
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的網(wǎng)站標準答案:
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();
}
}
最后還是發(fā)現(xiàn)了Python的解法,原來是用split和slice對local_address和domain兩個字符串進行重新構(gòu)造,代碼如下:
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)
完畢,晚安。