Leetcode 8. String to Integer (atoi)

Leetcode 8. String to Integer

题目说明

Implement atoi which converts a string to an integer.
题目可以简短概括为将一个输入的字符串转化为数值型输出,其中特殊情况有:
1.首字符可以是空格/数字/正负符号(有效输入为多空格直至出现后面两种情况之一)
2.首字符一旦不是上述三种情况之一直接返回0
3.最后输出的数值有32位有符号整数值范围限制
4.连续‘±’或‘-+’情况则视为无效输出返回0

总结:本题没有任何逻辑或者是技术上的难度
(个人水平有限,一直在通过各种if判断来裁定边界情况)

代码部分1

class Solution:
    def myAtoi(self, str: 'str') -> 'int':
            c=1
            oc = -1
            out = ''
            for i in str:
                if i==' ' or i=='-' or i=='+' or (i >='0' and i <= '9'):
                    #print('ok')
                    if oc>0:
                        if (i<'0' or i>'9'):break
                    if i=='-':
                        c=-1
                        oc=1
                        continue
                    if i=='+':
                        c=1
                        oc=1
                        continue
                    if i >='0' and i <= '9':
                        out += i
                        oc=1
                        continue
                else:break
            if oc<0 or out=='':
                return 0
            else:            
                out = c*int(out)
                if out<-2**31:
                    return -2**31
                elif out>2**31-1:
                    return 2**31-1
                else:
                    return out

Runtime: 56 ms, faster than 98.53% of Python3 online submissions for String to Integer (atoi).

Memory Usage: 12.6 MB, less than 37.95% of Python3 online submissions for String to Integer (atoi).

emmm解题思路不做评价

代码部分2

class Solution:
    def myAtoi(self, str):   
        ret = re.search('^(([+|-]\d+)|\d+)',str.strip())
        #strip移除字符串头尾指定的字符序列(默认为空格或换行符)
        #search在字符串中寻找模式匹配(返回第一个匹配)
        #^放在开头表示后续匹配内容必须是以要求匹配模式开头的字符串
        #+表示多个字符
        #[+|-]\d+表示+或者-带一堆数字
        #\d+纯一堆数字
        if ret:
            ret = ret.group()
            ret_int = int(ret)
        else:
            ret_int = 0
        if ret_int > 2147483647:
            ret_int = 2147483647
        elif ret_int < -2147483648:
            ret_int = -2147483648
        return ret_int

Runtime: 52 ms, faster than 100.00% of Python3 online submissions for String to Integer (atoi).

Memory Usage: 12.6 MB, less than 45.68% of Python3 online submissions for String to Integer (atoi).

思路解析:
大佬就是大佬
还有正则表达式真的是强者一般的存在!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值