leetcode簡單(181-200)python
762. Prime Number of Set Bits in Binary Representation(e-181)
Given two integers L
and R
, find the count of numbers in the range [L, R]
(inclusive) having a prime number of set bits in their binary representation.
(Recall that the number of set bits an integer has is the number of 1
s present when written in binary. For example, 21
10101
which has 3 set bits. Also, 1 is not a prime.)
class Solution(object): def countPrimeSetBits(self, L, R): """ :type L: int :type R: int :rtype: int """ b=0 c=[2, 3, 5, 7, 11, 13, 17, 19, 23, 31, 37] for i in range(L, R+1): a=bin(i).count("1") if a in c: b+=1 return b
766. Toeplitz Matrix(e-182)
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
Now given an M x N
matrix, return True
if and only if the matrix is Toeplitz.
class Solution(object): def isToeplitzMatrix(self, matrix): """ :type matrix: List[List[int]] :rtype: bool """ for i in range(len(matrix)-1): for j in range(len(matrix[0])-1): if matrix[i][j]!=matrix[i+1][j+1]: return False return True
771. Jewels and Stones(e-183)
You're given strings J
representing the types of stones that are jewels, and S
representing the stones you have. Each character in S
is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J
are guaranteed distinct, and all characters in J
and S
are letters. Letters are case sensitive, so "a"
is considered a different type of stone from "A"
.
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
return sum(s in J for s in S)
783. Minimum Distance Between BST Nodes(e-184)---------
Given a Binary Search Tree (BST) with the root node root
, return the minimum difference between the values of any two different nodes in the tree.
784. Letter Case Permutation(e-185)
Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.
class Solution(object):
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
ans = []
def dfs(S, pos, str):
if pos == len(S):
ans.append(str)
return
else:
if S[pos].isalpha():
letter = S[pos]
dfs(S, pos + 1, str + letter.upper())
dfs(S, pos + 1, str + letter.lower())
else:
dfs(S, pos + 1, str + S[pos])
dfs(S, 0, '')
return ans
788. Rotated Digits(e-186)
X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone.
A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.
Now given a positive number N
, how many numbers X from 1
to N
are good?
class Solution(object):
def rotatedDigits(self, N):
"""
:type N: int
:rtype: int
112ms
"""
count = 0
for i in range(1, N + 1):
s = str(i)
num = 0
for char in s:
if char in '347':
num = -1
break
elif char in '018':
num += 1
# 判斷是否有效,和是否相同
if num != len(s) and num != -1:
count += 1
return count
796. Rotate String(e-187)
We are given two strings, A
and B
.
A shift on A
consists of taking string A
and moving the leftmost character to the rightmost position. For example, if A = 'abcde'
, then it will be 'bcdea'
after one shift on A
. Return True
if and only if A
can become B
after some number of shifts on A
.
class Solution(object):
def rotateString(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
m,n = len(A),len(B)
if m!=n:
return False
if A == B:
return True
for i in range(1,m):
if A[i:] + A[0:i] == B:
return True
return False
804. Unique Morse Code Words(e-188)
nternational Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a"
maps to ".-"
, "b"
maps to "-..."
, "c"
maps to "-.-."
, and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cab" can be written as "-.-.-....-", (which is the concatenation "-.-." + "-..." + ".-"). We'll call such a concatenation, the transformation of a word.
Return the number of different transformations among all words we have.
class Solution(object):
def uniqueMorseRepresentations(self, words):
"""
:type words: List[str]
:rtype: int
"""
ref=[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
return len(set("".join(ref[ord(s)-97] for s in word) for word in words))
806. Number of Lines To Write String(e-189)
We are to write the letters of a given string S
, from left to right into lines. Each line has maximum width 100 units, and if writing a letter would cause the width of the line to exceed 100 units, it is written on the next line. We are given an array widths
, an array where widths[0] is the width of 'a', widths[1] is the width of 'b', ..., and widths[25] is the width of 'z'.
Now answer two questions: how many lines have at least one character from S
, and what is the width used by the last such line? Return your answer as an integer list of length 2.
class Solution:
def numberOfLines(self, widths, S):
"""
:type widths: List[int]
:type S: str
:rtype: List[int]
"""
cur_width=0
cur_line=1
for letter in S:
width=widths[ord(letter)-ord('a')]
cur_line=cur_line+1 if cur_width+width>100 else cur_line
cur_width=width if cur_width+width>100 else cur_width+width
return cur_line,cur_width
811. Subdomain Visit Count(e-190)
A website domain like "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com", and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.
Now, call a "count-paired domain" to be a count (representing the number of visits this domain received), followed by a space, followed by the address. An example of a count-paired domain might be "9001 discuss.leetcode.com".
We are given a list cpdomains
of count-paired domains. We would like a list of count-paired domains, (in the same format as the input, and in any order), that explicitly counts the number of visits to each subdomain.
class Solution(object):
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
domain_counts = collections.defaultdict(int)
for cpdomain in cpdomains:
times, domains = cpdomain.split()
times = int(times)
domain_counts[domains] += times
while '.' in domains:
domains = domains[domains.index('.') + 1:]
domain_counts[domains] += times
return [str(v) + ' ' + d for d, v in domain_counts.items()
812. Largest Triangle Area(e-191)
You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points.
class Solution(object):
def calArea(self, p1, p2, p3):
#Use Determinant to get triangle area
return .5 * abs(p1[0] * p2[1] + p2[0] * p3[1] + p3[0] * p1[1] - p1[0] * p3[1] - p2[0] * p1[1] - p3[0] * p2[1])
def largestTriangleArea(self, points):
"""
:type points: List[List[int]]
:rtype: float
"""
maxS = 0
for i in range(len(points) - 2):
for j in range(i + 1, len(points) - 1):
for k in range(j + 1, len(points)):
S = self.calArea(points[i], points[j], points[k])
if S > maxS:
maxS = S
return maxS
819. Most Common Word(e-192)
Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.
lass Solution:
def mostCommonWord(self, paragraph, banned):
"""
:type paragraph: str
:type banned: List[str]
:rtype: str
"""
p = re.compile(r"[!?',;.]")
sub_para = p.sub('', paragraph.lower())
words = sub_para.split(' ')
words = [word for word in words if word not in banned]
count = collections.Counter(words)
return count.most_common(1)[0][0]
821. Shortest Distance to a Character(e-193)
Given a string S
and a character C
, return an array of integers representing the shortest distance from the character C
in the string.
class Solution(object):
def shortestToChar(self, S, C):
"""
:type S: str
:type C: str
:rtype: List[int]
"""
index_nums=[]
for i, letter in enumerate(S):
if letter==C:
index_nums.append(i)
ans=[]
for j, word in enumerate(S):
distance=(abs(j-index_num) for index_num in index_nums)
ans.append(min(distance))
return ans
824. Goat Latin(e-194)
A sentence S
is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
- If a word begins with a vowel (a, e, i, o, or u), append
"ma"
to the end of the word.
For example, the word 'apple' becomes 'applema'.
- If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add
"ma"
.
For example, the word"goat"
becomes"oatgma"
.
- Add one letter
'a'
to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets"a"
added to the end, the second word gets"aa"
added to the end and so on.
Return the final sentence representing the conversion from S
to Goat Latin.
class Solution(object):
def toGoatLatin(self, S):
"""
:type S: str
:rtype: str
"""
vowels=['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
words=S.split()
new_words=[]
for i, word in enumerate(words):
if word[0] in vowels:
word+='ma'
else:
word=word[1:]+word[0]+'ma'
word+='a'*(i+1)
new_words.append(word)
return ' '.join(new_words)
830. Positions of Large Groups(e-195)
In a string S
of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like S = "abbxxxxzyy"
has the groups "a"
, "bb"
, "xxxx"
, "z"
and "yy"
.
Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group.
The final answer should be in lexicographic order.
class Solution:
def largeGroupPositions(self, S):
"""
:type S: str
:rtype: List[List[int]]
"""
groups = []
before_index, before_char = 0, S[0]
for i, s in enumerate(S):
if s != before_char:
if i - before_index >= 3:
groups.append([before_index, i - 1])
before_index = i
before_char = s
if i - before_index >= 2:
groups.append([before_index, i])
return groups
832. Flipping an Image(e-196)
Given a binary matrix A
, we want to flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0]
horizontally results in [0, 1, 1]
.
To invert an image means that each 0
is replaced by 1
, and each 1
is replaced by 0
. For example, inverting [0, 1, 1]
results in [1, 0, 0]
.
class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
for i in range(len(A)):
for j in range(len(A[i])):
A[i][j] = abs(1 - A[i][j])
for k in range(int(len(A[i])/2)):
A[i][k], A[i][len(A[i])-1-k] = A[i][len(A[i])-1-k], A[i][k]
return A
836. Rectangle Overlap(e-197)
A rectangle is represented as a list [x1, y1, x2, y2]
, where (x1, y1)
are the coordinates of its bottom-left corner, and (x2, y2)
are the coordinates of its top-right corner.
Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two rectangles, return whether they overlap.
class Solution:
def isRectangleOverlap(self, rec1, rec2):
"""
:type rec1: List[int]
:type rec2: List[int]
:rtype: bool
"""
rec1_x1, rec1_y1, rec1_x2, rec1_y2 = rec1
rec2_x1, rec2_y1, rec2_x2, rec2_y2 = rec2
return not (rec1_x1 >= rec2_x2 or rec1_x2 <= rec2_x1 or rec1_y1 >= rec2_y2 or rec1_y2 <= rec2_y1)
840. Magic Squares In Grid(e-198)
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given an grid
of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
class Solution(object):
def numMagicSquaresInside(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if len(grid)<3 and len(grid[0])<3:
return 0
counter=0
for row in range(len(grid)-2):
for col in range(len(grid[0])-2):
sub_matrix=[[grid[row+i][col+j]for j in range(3)]for i in range(3)]
if self.magic_square(sub_matrix):
counter+=1
return counter
def magic_square(self, matrix):
is_number_right=all(1<=matrix[i][j]<=9 for i in range(3) for j in range(3))
is_row_right=all(sum(row)==15 for row in matrix)
is_col_right=all(sum(col)==15 for col in [[matrix[i][j]for i in range(3)]for j in range(3)])
is_diagonal_right = matrix[1][1] == 5 and matrix[0][0] + matrix[-1][-1] == 10 and matrix[0][-1] + matrix[-1][0] == 10
return is_number_right and is_row_right and is_col_right and is_diagonal_right
844. Backspace String Compare(e-199)
Given two strings S
and T
, return if they are equal when both are typed into empty text editors. #
means a backspace character.
class Solution(object):
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
ans_S = ""
ans_T = ""
for s in S:
if s == '#':
if ans_S:
ans_S = ans_S[:-1]
else:
ans_S += s
for t in T:
if t == '#':
if ans_T:
ans_T = ans_T[:-1]
else:
ans_T += t
return ans_S == ans_T
849. Maximize Distance to Closest Person(e-200)
In a row of seats
, 1
represents a person sitting in that seat, and 0
represents that the seat is empty.
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
Return that maximum distance to closest person.
class Solution(object):
def maxDistToClosest(self, seats):
"""
:type seats: List[int]
:rtype: int
"""
index = -200000
_len = len(seats)
ans = [0] * _len
for i in range(_len):
if seats[i] == 1:
index = i
else:
ans[i] = abs(i - index)
index = -200000
for i in range(_len - 1, -1, -1):
if seats[i] == 1:
index = i
else:
ans[i] = min(abs(i - index), ans[i])
return max(ans)