jz067.把字符串转换成整数 Leetcode Oct 21, 2020 题目链接 这个题不难但是要排除各种特殊情况,比如空字符串,数字大于或小于特定值等。如一所示是我丑陋的实现,注意从str转换到int既然不能用int()那么可以用ord(s)去和ord(“0”)去做差。这个算法的时间复杂度是O(N),空间复杂度是O(N)。如2是别人优雅的实现,因为去除了strip()函数所以空间复杂度也降到了O(1)。 class Solution: def strToInt1(self, s: str) -> int: s = s.strip(" ") intmax, intmin = 2**31 - 1, -2**31 if not s: return 0 if s[0] not in "-+0123456789": return 0 else: res = 0 if s[0] in "-+": sign = -1 if s[0] == "-" else 1 i = 1 while i < len(s) and s[i] in "0123456789": res *= 10 res += ord(s[i]) - ord("0") i += 1 if sign * res > intmax: return intmax elif sign * res < intmin: return intmin return sign * res i = 0 while i < len(s) and s[i] in "0123456789": res *= 10 res += ord(s[i]) - ord("0") i += 1 if res > intmax: return intmax return res def strToInt2(self, str: str) -> int: res, i, sign, length = 0, 0, 1, len(str) int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10 if not str: return 0 # 空字符串,提前返回 while str[i] == ' ': i += 1 if i == length: return 0 # 字符串全为空格,提前返回 if str[i] == '-': sign = -1 if str[i] in '+-': i += 1 for c in str[i:]: if not '0' <= c <= '9' : break if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min res = 10 * res + ord(c) - ord('0') return sign * res PREVIOUSjz066.构建乘积数组NEXTjz068I.二叉搜索树的最低公共祖先