Leetcode上的一道中等难度的题,题目限制非常多。
原题链接:https://leetcode.com/problems/string-to-integer-atoi/#/description
题目要求:Implement atoi to convert a string to an integer (把输入的字符串转换为整数)
题目限制:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
1. 若字符串开头是空格,则跳过所有空格,到第一个非空格字符,如果没有,则返回0.
2. 当异常字符(非0-9之间的数)出现时,从异常字符开始截断后面所有字符,只转换异常字符之前的字符为整数,但要注意+、-可以作为整形数开头;3.还需要考虑边界问题,如果超过了整形数的范围[-2147483648,2147483647],则用边界值替代当前值。
这题就是坑比较多,诸多情况不能一下子完全考虑到,比如" +10"可以转换。但“+ 10”就不能转换,“123a456”就只能转换“123”了,限制情况都明了,自然好解,先来一个我自己的方法,把所有情况考虑进去,
Python 解法一(直接法,58ms):
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
str = str.strip() #去除字符串前面空格
len_str = len(str)
int_set = ['0','1','2','3','4','5','6','7','8','9']
atoi = '0'
atoi_max = 2147483647
atoi_min = -2147483648
if len_str > 0:
i = 0
if str[0] in ["+","-"]: #判断字符串带"+" or "-"号
i = 1
atoi = str[0] + atoi
for j in range(i,len_str):
if str[j] in int_set:
atoi = atoi + str[j]
else:
break
atoi = int(atoi)
if atoi > atoi_max: #判断溢出
atoi = atoi_max
if atoi < atoi_min:
atoi = atoi_min
return atoi
Leetcode上有个哥们用的正则,也是超赞的,正则^[+\-]表示匹配开头是+或-号,?代表匹配0或1次,\d代表匹配0-9的整数,+代表1或多个。值得一提的是正则中取反,是用[^ 排除内容],如:[^ \d]排除数字。
Python 解法二(正则):
class Solution:
# @return an integer
def atoi(self, str):
str = str.strip()
str = re.findall('^[+\-]?\d+', str)
try:
result = int(''.join(str))
MAX_INT = 2147483647
MIN_INT = -2147483648
if result > MAX_INT > 0:
return MAX_INT
elif result < MIN_INT < 0:
return MIN_INT
else:
return result
except:
return 0
欢迎讨论