从寒假凯旋君说要和我一起刷算法题,中间搁置到现在重新捡起,希望自己能给自己一个答复吧,别让自己沉沦。
它是python的内置函数,用在字典上是枚举、列举的意思,对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值,enumerate多用于在for循环中得到计数。
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1):
print index, item
r = int(str(x)[::-1])
注意:负数不是回文
题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
'''
解题思路:将罗马数字转换成对应的整数。首先将罗马数字翻转,从小的开始累加,如果遇到CM(M-C=1000-100=900)这种该怎么办呢?因为翻转过来是MC, M=1000先被累加,所以使用一个last变量,把M记录下来,如果下一个数小于M,那么减两次C,然后将C累加上,这个实现比较巧妙简洁。
'''
numerals = { "M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1 }
sum=0
s=s[::-1]
last=None
for x in s:
if last and numerals[x]2*numerals[x]
sum+=numerals[x]
last=numerals[x]
return sum
它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),
第0个元组对应于所有参数的第0个元素,第1个元组对应于所有参数的第1个元素,依此类推,然后返回由这些tuples组成的list(列表)。
若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。
题目:
Write a function to find the longest common prefix string amongst an array of strings.
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
res = ""
for k in zip(*strs):
if len(set(k)) == 1:
res = res + k[0]
else:
break
return res
题目:
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
map = {')':'(', '}':'{', ']':'['}
st = []
for e in s:
if st and (e in map and st[-1] == map[e]):
st.pop()
else:
st.append(e)
return not st
Python算法实战系列之栈