Leetcode 13-14

5 篇文章 0 订阅
4 篇文章 0 订阅

这两天刷了一下leetcode的两道easy题。记录一下。

13. Roman to Integer 

  • 题目13

Roman numerals are represented by seven different symbols: IVXLCD and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: "III"
Output: 3

Example 2:

Input: "IV"
Output: 4

Example 3:

Input: "IX"
Output: 9

Example 4:

Input: "LVIII"
Output: 58
Explanation: C = 100, L = 50, XXX = 30 and III = 3.

Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
  • 分析

最开始的时候,我利用了最笨的方法,按照两个字符的方式读取,判断。写了很多的判断。最终也算是可以AC了。但是看了别人的代码,瞬间觉得自己的很low。1、是别人利用了字典这一数据结构,而我却在用判断,用switch case语句。2、是别人发现了数字之间的规律:只要前面的字符小于后面的就减,否则加。

  • 自己的代码:

def convert(first,second):
        """
        Args:
            first : the first character
            second :the next character after the first one
        Return:
            the result of convert
        """
        flag = 0
        if first == 'I':
            if second == 'V':
                number = 4
                flag = 1
            elif second =='X':
                number = 9
                flag = 1
            else:
                number = 1
        elif first == 'X':
            if second == 'L':
                number = 40
                flag = 1
            elif second =='C':
                number = 90
                flag = 1
            else:
                number = 10
        elif first == 'C':
            if second == 'D':
                number = 400
                flag = 1
            elif second =='M':
                number = 900
                flag = 1
            else:
                number = 100
        elif first == 'V':
            number = 5
        elif first == 'L':
            number = 50
        elif first == 'D':
            number = 500
        elif first == 'M':
            number = 1000
        else:
            number =0
        
        return number,flag

class Solution(object):

    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        count = 0
        sum_Number = 0
        while(count<len(s)-1):
            num_temp,flag= convert(s[count],s[count+1])
            if flag == 1:
                count+=2
            else :
                count+=1
            sum_Number+=num_temp
        if count < len(s):
            num_temp,flag = convert(s[count],s[count])
            sum_Number+=num_temp
        return sum_Number
  • 别人的代码:

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dict_Roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
        sum_all = dict_Roman[s[len(s)-1]]
        for i in range(0,len(s)-1):
            if(dict_Roman[s[i]] < dict_Roman[s[i+1]]):
                sum_all -= dict_Roman[s[i]]
            else:
                sum_all += dict_Roman[s[i]]
        return sum_all

14. Longest Common Prefix

  • 题目14

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

  • 分析

我最开始直接就利用了一个二重循环进行了处理,先比较字符串,在比较字符。别人虽然同样用的这个方式,但是是把最短的字符串和其他字符串进行了比较。相当他把二重循环的顺序进行了一下颠倒,程序的效率就提高了,同时他的代码写的也很清晰易读。

  • 自己的代码

class Solution:
    def compareString(first,second):
        """
        :type first: the first character
        :type second:the second character
        :rtype: str
        """
        commonChar = ""
        if not first == None and not second == None:
            char_range = min(len(first),len(second))
        else:
            return ""
        for i in range(0,char_range):
            if first[i] == second[i]:
                commonChar = commonChar + first[i]
                if i == char_range - 1:
                    return commonChar
            else:
                return commonChar
        
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs) > 0:
            common = strs[0]
        else:
            return ""
        for i in range(1,len(strs)):
            temp = strs[i]
            common = Solution.compareString(common,temp)
            
        if common == None:
            return ""
        else:
            return common 
  • 别人的代码

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ""
        shortest = min(strs,key=len)
        for i ,ch in enumerate(shortest):
            for others  in strs:
                if others[i] != ch:
                    return shortest[:i]
        return shortest

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值