辣雞劉的Leetcode之旅7【Length of Last Word,Maximum Subarray,count-and-say】

58. Length of Last Word

題目描述:

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

Example:

Input: "Hello World"
Output: 5

這個很簡單:

class Solution:
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        str = s.split()
        if len(str)==0:
            return 0
        else:
            return len(str[-1])

一行代碼也可以:

def lengthOfLastWord(self, s):
    return len(s.rstrip(' ').split(' ')[-1])

## 53. Maximum Subarray ##```
題目描述:

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.


動態規劃,這個我不太會:

class Solution:
def maxSubArray(self, nums):
“””
:type nums: List[int]
:rtype: int
“””
for i in range(1,len(nums)):
if nums[i-1]>0:
nums[i]+=nums[i-1]
return max(nums)

註釋:動態規劃,漢諾塔之類的字眼,師兄師姐做筆試題成天遇到,貌似很重要,嘿嘿

## count-and-say ##

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 111221
    1 is read off as “one 1” or 11.
    11 is read off as “two 1s” or 21.
    21 is read off as “one 2, then one 1” or 1211.

Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

題目稍微有點不容易理解,就是1讀作1111讀作21既是:2121讀作12111211,以此類推......

class Solution:
def countAndSay(self, n):
“””
:type n: int
:rtype: str
“””
s = ‘1’
for _ in range(n - 1):
s = ”.join(str(len(list(group))) + digit
for digit, group in itertools.groupby(s))
return s
“`

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章