Leetcode 20181025

Oct 25, 2018

https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/646/

Strings

First Unique Character in a String

暂不做优化,啥时候要炫技吓人再说:

count = {}
for i, j in enumerate(s):
    if j in count:
        count[j] += 1
    else:
        count[j] = 1
for i, j in enumerate(s):
    if count[j] == 1:
        return i
return -1

做完之后看到有别人用 set,find 和 rfind 来提高效率,以后可以参考。

Valid Anagram

我这个答案不说效率,应该是最精简的了:

return sorted(s) == sorted(t)

而且效率也不算很低:

Your runtime beats 31.55 % of python3 submissions.

顺便提交到了评论区,看看别人的看法:

https://leetcode.com/explore/featured/card/top-interview-questions-easy/127/strings/882/discuss/185617/Python-1-line-(using-only-1-built-in-function)

Valid Palindrome

排除了字母和数字之外的数据之后,就好办了:

j = ''
for i in s:
    if i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789':
        j += i.lower()
k = j[::-1]
for i in range(0, len(j)):
    if j[i] != k[i]:
        return False
return True

做完之后看到有人用 ‘’.isalpha() 和 ‘’.isdigit() 两个函数,写起来可以更加精简。

String to Integer (atoi)

一点 Debug code in playground 之后,第一眼就看到了:

def myAtoi(self, str):
    """
    :type str: str
    :rtype: int

估计 leetcode 的题目 Python 基础代码是自动生成的,才会出现变量名和 Python 关键字冲突的情况。

这题的 cases 也太变态了吧 …

1024 / 1079 test cases passed. Input: “-5-” Output: 0 Expected: -5

我整个人都 -5- 了!

果然有人抱怨了:

https://leetcode.com/explore/featured/card/top-interview-questions-easy/127/strings/884/discuss/4640/Such-a-shitty-problem

1077 / 1079 test cases passed. Input: “-13+8” Output: 0 Expected: -13

简直了,这玩意是数字?!说好的 atoi 呢?问题是之前有个 case 是

Input: “1-1” Expected: 0

的呀??

这都 1000 多个 case 了,所以是大家开始互相伤害了吗?

过了,就这样吧:

s = s.strip().rstrip('+').rstrip('-')
found = False
found_num = False
found_sym = False
sections = 0
in_section = False
allowed = '0123456789-+'
symbol = ['-', '+']
symbols = 0
res = ''
last = None
for i in s:
    if i not in allowed:
        break
    if i in allowed:
        found = True
        res += i
    if i.isdigit():
        if not in_section:
            in_section = True
            sections += 1
        found_num = True
    if in_section and not i.isdigit():
        in_section = False
        sections += 1
    if i in symbol:
        if last in symbol:
            return 0
        found_sym = True
        symbols += 1
    last = i
print(res, found, sections, symbols)
if sections - symbols == 1:
    res = res.split('+')[0] # useless code
elif not res or not found or not found_num or sections > 2:
    return 0
res = int(res.rstrip('-+'))
if res > (1 << 31) - 1:
    res = (1 << 31) - 1
elif res < -1 << 31:
    res = -1 << 31
return res

[back]