这次的三道题都不是很难,属于那种一眼就能看出思路,只是方法是否最优的问题。说实话,这三道题更应该用C/C++来做,因为考察的都是字符串的基本功。不过我很久没用C系语言了,一时半会实在搞不定这个指针。大python嘛,无脑过就行了。所以这次我更侧重python如何用更少的代码量,更简洁的方式解决这些问题。当然,虽然python很好用,但用的时候一定要搞清楚它的性能瓶颈,这样子遇到问题才知道怎么解决,就比如第八题我所用的正则。
leetcode 007
代码实现
这道题要是用C/C++,最佳做法不是用指针一个个读,而是利用十位制的一些性质。用python就很无脑了。
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ s = str(abs(x))[::-1] result = int(s) if x > 0 else -int(s) if result < -2**31 or result >= 2**31: result = 0 return result
说实话,因为python语言设定的,这道题要用C的那种做法相当麻烦。正是因为这样,我深刻理解了,一门语言就该干它擅长的活,python就应该写得飘起来,而不是像C一样斤斤计较。
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ maxint = 2**31 rev = 0 while x: if x > 0: x, pop = x // 10, x % 10 else: x, pop = -(abs(x)//10) , -(abs(x) % 10) if rev > maxint // 10 or (rev == maxint // 10 and pop > 7): return 0 if rev < -(maxint // 10) or (rev == -(maxint // 10) and pop < -8): return 0 rev = rev * 10 + pop return rev
leetcode 008
代码实现
这道题要是中规中矩按照题目原设定的做法去做,要卡好几次边界。对于这类匹配问题,我一下子就想到了正则匹配。这道题用正则匹配就很无脑了。
class Solution: def myAtoi(self, str): """ :type str: str :rtype: int """ import re try: str = str.strip() pos = re.match(r'^([-+]?)(\d)+', str).span() ret = int(str[pos[0]:pos[1]]) if ret >= 2**31: return 2**31-1 elif ret < -2**31: return -2**31 return ret except: return 0
但是正则匹配有一个,那就是写匹配时要慎用贪婪匹配!不然会产生严重的性能问题,不过在这道题上还好,性能降得不是特别厉害。
leetcode 009
代码实现
属于回文串问题。代码 x = ' '.join(list(str(x)))
是在每两个字符插入空格,在本题中多余,但用来处理大多数回文串问题都非常高效。
class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ x = ' '.join(list(str(x))) rev_x = x[::-1] if x == rev_x: return True else: return False