LeetCode刷题记录-20181021

119. Pascal's Triangle II  

返回杨辉三角第n层数字列表,和118类似

 1 class Solution:
 2     def getRow(self, rowIndex):
 3         """
 4         :type rowIndex: int
 5         :rtype: List[int]
 6         """
 7         if rowIndex== 0:
 8             return [1]
 9         else:
10             result = []
11             temp = self.getRow(rowIndex-1)
12             temp = [0] + temp
13             temp.append(0)
14             for i in range(len(temp)-1):
15                 result.append(temp[i]+temp[i+1])
16             return result
View Code

121. Best Time to Buy and Sell Stock 

O(n)时间复杂度,列表中最小值为买点,依次迭代列表,找到最大利润。注意:只能买卖一次

 1 class Solution:
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         profit = 0 
 8         m = len(prices)
 9         if m==0:
10             return 0
11         local_profit = 0
12         buypoint = prices[0]
13         for i in range(1,m):
14             if prices[i]<buypoint:
15                 buypoint = prices[i]
16             local_profit = prices[i]-buypoint
17             if local_profit>profit:
18                 profit = local_profit
19         return profit
View Code

122.Best Time to Buy and Sell Stock II 

可以买卖多次,卖完之后才可以买入。最大利润为所有差值为正的和

 1 class Solution:
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         sum = 0 
 8         m = len(prices)
 9         for i in range(m-1):
10             temp = prices[i+1]-prices[i]
11             if temp >0:
12                 sum += temp
13         return sum
14         
View Code

125.Valid Palindrome

判断是否为回文(字符串包含空格、标点符号),判断字符是否为字符串或者数字,a.isalnum()

方法1:设定两个指针,头指正,尾指针,判断当前位置是否满足字符或者数字,如满足,判断头尾是否相同(注意大小写);如不满足,头指正加1,尾指针减一,O(n)时间复杂度

 1 class Solution:
 2     def isPalindrome(self, s):
 3         """
 4         :type s: str
 5         :rtype: bool
 6         """
 7         m = len(s)
 8         if m == 0:
 9             return True
10         left_tag = 0
11         right_tag = m -1
12         
13         while left_tag <= right_tag:
14             left_letter = s[left_tag]
15             right_letter = s[right_tag]
16             if not left_letter.isalnum():
17                 left_tag+=1
18                 continue
19             if not right_letter.isalnum():
20                 right_tag-=1
21                 continue
22         
23             if left_letter.upper() != right_letter.upper():
24                 return False
25             else:
26                 left_tag +=1
27                 right_tag -=1              
28         
29         return True
方法1

方法2:正则表达式,剔除非数字和字母字符,翻转后对比

1 class Solution:
2     def isPalindrome(self, s):
3         """
4         :type s: str
5         :rtype: bool
6         """
7         s = re.sub('[^a-zA-Z0-9]', '', s).lower()
8         return s[::-1] == s
方法2

 

posted @ 2018-10-21 19:02  adminyzz  阅读(77)  评论(0编辑  收藏  举报