https://leetcode-cn.com/problems/string-to-integer-atoi/

代码:

# -*- coding:utf-8 -*-
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
import re
return max(min(int(*re.findall('^[\+\-]?\d+', str.lstrip())), 2**31 - 1), -2**31)


if __name__ == '__main__':
s = ' -4193 with words'
print(Solution().myAtoi(s))
pass

思路:这道题比较简单,正则一下前几个匹配项然后转成int函数即可。

对于正则,‘^[\+\-]?\d+’,前置匹配+或者-符号,然后使用非贪婪模式,也就是只匹配尽可能少个,然后匹配数字。

分类: 算法

0 条评论

发表回复

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用 * 标注