第26题:删除数组的重复项
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
while i < (len(nums)-1):
if nums[i] == nums[i+1]:
nums.remove(nums[i])
else:
i += 1
return len(nums)
第27题:移除元素
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
sorted(nums)
i = 0
while (i < len(nums)):
if nums[i] == val:
nums.remove(nums[i])
else:
i += 1
return len(nums)
第28题:实现strStr()
方法一:
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if len(needle)==0:
return 0
if (len(needle) > len(haystack)):
return -1
a = -1
for i in range(len(haystack)):
if haystack[i:i+len(needle)] == needle:
a = i
return a
if a == -1:
return -1
方法二:
if needle not in haystack:
return -1
return haystack.find(needle)