今天开始加快速度,趁着还有空多刷几题,语言换成python提高速度了。
1. Unique Email Addresses
弱题,注意@符号前后的处理方式不同
class Solution(object): def numUniqueEmails(self, emails): """ :type emails: List[str] :rtype: int """ ret = set() for i in emails: name, mail = i.split('@') x = name.replace('.', '').split('+')[0] + '@' + mail ret.add(x,) return len(ret)
2. To Lower Case
直接用python的lower,但是我想原意应该是用ASCII码表转换。
代码就不贴了,一行。
3. Encode and Decode TinyURL
这个稍微难一点点,但是本质还是弱题,建一个dict就好了,如果是真实的框架,应该需要考虑分区和分块、缓存等等。
class Codec: urlMap = {} countMap = {} count = 0 defaultUrl = 'http://tinyurl.com/' def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str """ if longUrl in self.urlMap: return self.defaultUrl + str(self.urlMap[longUrl]) self.urlMap[longUrl] = str(self.count) self.countMap[str(self.count)] = longUrl self.count += 1 return self.defaultUrl + str(self.urlMap[longUrl]) def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str """ key = shortUrl.split('/')[-1] return self.countMap.get(key) # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(url))