• leetcode 007-009


    这次的三道题都不是很难,属于那种一眼就能看出思路,只是方法是否最优的问题。说实话,这三道题更应该用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
    
  • 相关阅读:
    matlab 自定义函数及调用
    matlab 逻辑数组及其应用
    matlab 嵌套循环的学习
    matlab和C语言的break及continue测试
    matlab 向量法建数组(推荐)
    matlab for循环应用(阶乘及the day of year)
    matlab for循环的三种类型
    ORACLE创建用户,建表空间,授予权限
    Linux计划任务
    android开发环境搭建
  • 原文地址:https://www.cnblogs.com/ChanWunsam/p/10241683.html
Copyright © 2020-2023  润新知