classSolution(object): defmerge(self, intervals): """ :type intervals: List[List[int]] :rtype: List[List[int]] """ res = [] for i insorted(intervals,key = lambda x:x[0]): if res and i[0] <= res[-1][1]: res[-1][1] = max(res[-1][1],i[1]) else: res.append(i) return res
classSolution(object): definsert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ ifnot intervals orlen(intervals) == 0: return [newInterval] idx = -1 for i inrange(len(intervals)): if intervals[i].start > newInterval.start: idx = i break if idx != -1: intervals.insert(i, newInterval) else: intervals.append(newInterval) res = [] for interval in intervals: if res and res[-1].end >= interval.start: res[-1].end = max(res[-1].end, interval.end) else: res.append(interval) return res
3. 最后一个单词的长度(Easy)
给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
示例:
1 2
输入: "Hello World" 输出: 5
解答:
思路:
很简单
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): deflengthOfLastWord(self, s): """ :type s: str :rtype: int """ n = len(s) if n == 0: return0 res = 0 flag = 0 for i inrange(n-1,-1,-1): if s[i] != ' ': res += 1 flag = 1 elif s[i] == ' 'and flag: return res return res
思路二:
直接找最后一个单词
先找最后一个单词最后一个字母
再找最后一个单词第一个字母
1 2 3 4 5 6 7 8 9 10
classSolution: deflengthOfLastWord(self, s: str) -> int: end = len(s) - 1 while end >= 0and s[end] == " ": end -= 1 if end == -1: return0 start = end while start >= 0and s[start] != " ": start -= 1 return end - start
classSolution(object): defgenerateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ seen = [[False]*n for _ inrange(n)] dr = [0,1,0,-1] dc = [1,0,-1,0] r,c,di = 0,0,0 ans = [[-1]*n for _ inrange(n)] for i inrange(1,n*n+1): ans[r][c] = i seen[r][c] = True next_r,next_c = r+dr[di],c+dc[di] if0<= next_r<n and0<=next_c<n andnot seen[next_r][next_c]: r = next_r c = next_c else: di = (di+1)%4 r,c = r+dr[di],c+dc[di] return ans
classSolution(object): defgetPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ s = ''.join([str(i) for i inrange(1, n+1)]) print(s) defpermunation(s): iflen(s) == 0: return iflen(s) == 1: return [s] res = [] for i inrange(len(s)): x = s[i] xs = s[:i] + s[i+1:] for j in permunation(xs): res.append(x+j) return res return permunation(s)[k-1]
classSolution(object): defgetPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ res = '' fac = [1] * (n+1) for i inrange(1,n+1): fac[i] = fac[i-1]*i nums = [i for i inrange(1,n+1)] k -= 1 for i inrange(1,n+1): idx = k/fac[n-i] res += str(nums[idx]) nums.pop(idx) k -= idx * fac[n-i] return res