题目在leetcode上的链接为:
https://leetcode-cn.com/problems/string-to-integer-atoi/
题目描述
解题思路
这一题直接按照题目的流程去解题即可,算法步骤为:
- 找到第一个非空格出现的位置
- 从该位置开始遍历字符串,并用一个列表储存该位置开始的有效数字,直接遍历到第一个非有效数字结束
- 将列表转化为字符串后再使用 int 函数转化为整数,判断整数是否超限即可
复杂度分析:
由于需要遍历字符串直到第一个非有效数字的位置,所以时间复杂度为 o(n)
需要使用列表存储有效数字,空间复杂度为 o(n)
python代码:
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if str == '':
return 0
# 找到第一个非空格的位置
i = 0
while i < len(str) and str[i] == ' ' :
i = i + 1
res_list = []
if i < len(str) and (str[i] == '+' or str[i] == '-'):
res_list.append(str[i])
i = i + 1
while i < len(str) and str[i] >= '0' and str[i] <= '9':
res_list.append(str[i])
i = i + 1
if len(res_list) == 0 or (len(res_list) == 1 and (res_list[0] == '+' or res_list[0] == '-')):
return 0
res = int(''.join(res_list))
if res < -2**31:
return -2**31
elif res > 2**31 - 1:
return 2**31 - 1
else:
return res