class Solution: def twoSum(self, nums, target): for i in range(len(nums) - 1): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return i, j |
class Solution: def romanToInt(self, str): sum = 0 temp = str + " " for s in range(len(str)): if s == len(str) - 1: if temp[s] == "I": sum += 1 if s < len(str) - 1: if temp[s] == "I" and temp[s + 1] not in ("V", "X"): sum += 1 if s >= 1: if temp[s] == "X" and temp[s + 1] not in ("L", "C"): if temp[s - 1] == "I": sum += 9 else: sum += 10 elif temp[s] == "V": if temp[s - 1] == "I": sum += 4 else: sum += 5 elif temp[s] == "L": if temp[s - 1] == "X": sum += 40 else: sum += 50 elif temp[s] == "C" and temp[s + 1] not in ("D", "M"): if temp[s - 1] == "X": sum += 90 else: sum += 100 elif temp[s] == "D": if temp[s - 1] == "C": sum += 400 else: sum += 500 elif temp[s] == "M": if temp[s - 1] == "C": sum += 900 else: sum += 1000 else: if temp[s] == "X" and temp[s + 1] not in ("L", "C"): sum += 10 elif temp[s] == "V": sum += 5 elif temp[s] == "L" : sum += 50 elif temp[s] == "C" and temp[s + 1] not in ("D", "M"): sum += 100 elif temp[s] == "D": sum += 500 elif temp[s] == "M": sum += 1000 return sum |
因此其他狀況都不會有例外
那這樣就可以直接判斷任一區(qū)段的數(shù)字是否要加減
就不用像土法煉鋼還要看前後和位置
range(len(s) - 1, -1, -1)
是指從len(s) - 1 ~ -1 慢慢倒退使得 s[i] 是從後面數(shù)過來
class Solution: def romanToInt(self, s): romans = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} res = 0 prev = 0 for i in range(len(s) - 1, -1, -1): temp = romans[s[i]] if temp < prev: res -= temp else: res += temp prev = temp return res |
class Solution: def longestCommonPrefix(self, strs): if not strs: return "" strs.sort() first_str = strs[0] last_str = strs[-1] for i, char in enumerate(first_str): #["a","b","c"] -> [(0, "a"), (1, "b"), (2, "c")] if char != last_str[i]: return first_str[:i] return first_str |