58. 最后一个单词的长度
给定一个仅包含大小写字母和空格 ' '
的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
示例:
输入: "Hello World" 输出: 5
算法描述:将输入的字符串依据空格切片,切片返回一个列表,若列表为空,则return 0,若不为空,则return列表最后一个元素的长度
代码:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
l = s.split()
if len(l):
return len(l[-1])
else:
return 0
349. 两个数组的交集
给定两个数组,写一个函数来计算它们的交集。
例子:
给定 num1= [1, 2, 2, 1]
, nums2 = [2, 2]
, 返回 [2]
.
提示:
- 每个在结果中的元素必定是唯一的。
- 我们可以不考虑输出结果的顺序。
算法描述:建立一个空的列表result,遍历nums1和nums2,若存在相同的数且该数不在result中,则将该数加入result。
代码:
class Solution:
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result = []
for i in nums1:
for j in nums2:
if i == j and i not in result:
result.append(j)
return result