(13&14)-LeetCode-罗马数字转整数&最长公共前缀-python

(13&14)-LeetCode-罗马数字转整数&最长公共前缀-python

  • 13.题目如下
    (13&14)-LeetCode-罗马数字转整数&最长公共前缀-python_第1张图片
  • 代码
class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        IMMM
        """
        #考虑到数据了用字典,键值对分别为字符串和数字
        sum = 0
        convert = {'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1}
        for i in range(len(s)-1):
            #如果前一个字母小于后面的就减,否则加
            if convert[s[i]] < convert[s[i+1]]:
                sum -= convert[s[i]]
            else:
                sum += convert[s[i]]
        return sum + convert[s[-1]]

(13&14)-LeetCode-罗马数字转整数&最长公共前缀-python_第2张图片

  • 14.最长公共前缀
  • 题目如下
    (13&14)-LeetCode-罗马数字转整数&最长公共前缀-python_第3张图片
  • 代码
class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not(strs):
            return ""
        #定义一个列表
        l = list()
        i = 0
        len1 = len(strs[0])
        #先确定长度
        for s in strs:
            if (len1 > len(s)):
                len1 = len(s)
        while i <= len1-1:
            tmp = strs[0][i]
            for s in strs:
                if s[i] != tmp:
                    return ''.join(l)
            l.append(tmp)
            i = i+1
        return ''.join(l)

(13&14)-LeetCode-罗马数字转整数&最长公共前缀-python_第4张图片

你可能感兴趣的:(领扣刷题)