首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >LeetCode 8: String to Integer (atoi)

LeetCode 8: String to Integer (atoi)
EN

Code Review用户
提问于 2020-11-13 02:23:03
回答 2查看 321关注 0票数 3

我正在为LeetCode的“(atoi)”发布一个解决方案。如果你想复习,请看。谢谢!

问题

实现atoi,它将字符串转换为整数。在找到第一个非空白字符之前,函数首先根据需要丢弃尽可能多的空白字符。然后,从这个字符开始,取一个可选的正负号,后面跟着尽可能多的数字,并将它们解释为一个数值。字符串可以在构成整数的字符之后包含其他字符,这些字符被忽略,对此函数的行为没有任何影响。如果str中的第一个非空格字符序列不是有效整数,或者由于str为空或仅包含空白字符而不存在该序列,则不执行转换。如果无法执行有效的转换,则返回一个零值。

注:

只有空格字符“”被认为是空白字符。假设我们所处理的环境只能在32位有符号整数范围内存储整数:−231,231−1。如果数值超出可表示值的范围,则返回231−1或−231。

示例1:

代码语言:javascript
复制
Input: str = "42"
Output: 42

示例2:

代码语言:javascript
复制
Input: str = "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42.

示例3:

代码语言:javascript
复制
Input: str = "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

示例4:

代码语言:javascript
复制
Input: str = "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.

示例5:

代码语言:javascript
复制
Input: str = "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned.

代码语言:javascript
复制
from typing import List
import collections
import itertools
import functools
import math
import string
import random
import bisect
import re
import operator
import heapq
import queue

from queue import PriorityQueue
from itertools import combinations, permutations
from functools import lru_cache
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from collections import Counter


class Solution:
    def myAtoi(self, s):
        s = re.findall(r'^\s*[+-]?\d+', s)
        try:
            MAX, MIN = 2147483647, -2147483648
            res = int(''.join(s))
            if res > MAX:
                return MAX
            if res < MIN:
                return MIN
            return res
        except:
            return 0


if __name__ == "__main__":
    print(Solution().myAtoi("   -42"))

参考资料:

EN

回答 2

Code Review用户

回答已采纳

发布于 2020-11-13 03:21:23

不错的解决方案,它是紧凑和简单的理解。没有什么需要改进的,也没有什么建议:

  • 进口:有很多进口产品,可能是以前尝试的剩菜。
  • 试除块:应该在可能导致异常的代码周围。

应用这些建议:

代码语言:javascript
复制
import re

class Solution:
    def myAtoi(self, s: str) -> int:
        MAX, MIN = 2147483647, -2147483648
        s = re.findall(r'^\s*[+-]?\d+', s)
        try:
            res = int(''.join(s))
        except:
            return 0
        if res > MAX:
            return MAX
        if res < MIN:
            return MIN
        return res

性能

代码语言:javascript
复制
Runtime: 36 ms, faster than 51.56% of Python3 online submissions
Memory Usage: 14.1 MB, less than 32.27% of Python3 online submissions

Regex使代码紧凑,但不是最快的方法。更快的解决方案逐个字符遍历字符串。

票数 2
EN

Code Review用户

发布于 2020-11-13 15:22:35

幻数

代码语言:javascript
复制
2147483647, -2147483648

实际上

代码语言:javascript
复制
1<<31 - 1, -(1<<31)

这更好地传达了你的意图:有符号的32位整数的限制。

预编译regex

考虑把一个

代码语言:javascript
复制
DIGIT_PATTERN = re.compile(r'^\s*[+-]?\d+')

在全局范围内,这样对myAtoi的多次调用就会更快。

从未裸过except

您应该选择except ValueError,因为它更窄,定义也更好。

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/252031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档