題目在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