我正在为LeetCode的“(atoi)”发布一个解决方案。如果你想复习,请看。谢谢!
实现atoi,它将字符串转换为整数。在找到第一个非空白字符之前,函数首先根据需要丢弃尽可能多的空白字符。然后,从这个字符开始,取一个可选的正负号,后面跟着尽可能多的数字,并将它们解释为一个数值。字符串可以在构成整数的字符之后包含其他字符,这些字符被忽略,对此函数的行为没有任何影响。如果str中的第一个非空格字符序列不是有效整数,或者由于str为空或仅包含空白字符而不存在该序列,则不执行转换。如果无法执行有效的转换,则返回一个零值。
只有空格字符“”被认为是空白字符。假设我们所处理的环境只能在32位有符号整数范围内存储整数:−231,231−1。如果数值超出可表示值的范围,则返回231−1或−231。
Input: str = "42"
Output: 42Input: 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.Input: str = "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.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.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.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"))发布于 2020-11-13 03:21:23
不错的解决方案,它是紧凑和简单的理解。没有什么需要改进的,也没有什么建议:
应用这些建议:
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 resRuntime: 36 ms, faster than 51.56% of Python3 online submissions
Memory Usage: 14.1 MB, less than 32.27% of Python3 online submissionsRegex使代码紧凑,但不是最快的方法。更快的解决方案逐个字符遍历字符串。
发布于 2020-11-13 15:22:35
2147483647, -2147483648实际上
1<<31 - 1, -(1<<31)这更好地传达了你的意图:有符号的32位整数的限制。
考虑把一个
DIGIT_PATTERN = re.compile(r'^\s*[+-]?\d+')在全局范围内,这样对myAtoi的多次调用就会更快。
except您应该选择except ValueError,因为它更窄,定义也更好。
https://codereview.stackexchange.com/questions/252031
复制相似问题