这两天刷了一下leetcode的两道easy题。记录一下。
13. Roman to Integer
-
题目13
Roman numerals are represented by seven different symbols: I, V, X, L, C, D 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:
Ican be placed beforeV(5) andX(10) to make 4 and 9.Xcan be placed beforeL(50) andC(100) to make 40 and 90.Ccan be placed beforeD(500) andM(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

本文解析了LeetCode上两道经典题目:罗马数字转整数及寻找字符串数组中最长公共前缀的高效解决方案。通过对比不同解法,探讨了如何运用数据结构简化代码并提高效率。
491

被折叠的 条评论
为什么被折叠?



