""" # tle n = len(matrix) target = [i+1 for i in range(n)] target_count = Counter(target) for i in range(n): for j in range(n): tmp_counter1 = Counter(matrix[i]) tmp_counter2 = Counter([matrix[x][j] for x in range(n)]) if not (tmp_counter1 == target_count and tmp_counter2 == target_count): return False return True """
# 只判断对角线就够了? n = len(matrix) target = [i+1for i inrange(n)] target_count = Counter(target) for i inrange(n): tmp_counter1 = Counter(matrix[i]) tmp_counter2 = Counter([matrix[x][i] for x inrange(n)]) ifnot (tmp_counter1 == target_count and tmp_counter2 == target_count): returnFalse returnTrue
""" # TLE result_cnt = 0 none_counter = Counter("") counter_start_words = [Counter(x) for x in startWords] counter_target_words = [Counter(x) for x in targetWords] for i in range(len(counter_target_words)): flag = 0 for j in range(len(counter_start_words)): # 剪枝 if len(targetWords[i]) - len(counter_start_words[j]) != 1: continue if len([key for key in (counter_start_words[j] - counter_target_words[i]).keys()]) != 0: continue tmp_counter = counter_target_words[i] - counter_start_words[j] # 必须只有一个键,且这个键值为1,且这个不出现在原来的counter_target_words[i]中 key_list = [key for key in tmp_counter.keys()] if len(key_list) == 1 and tmp_counter[key_list[0]] == 1 and counter_start_words[j].get(key_list[0]) is None: flag = 1 break if flag == 1: result_cnt += 1 return result_cnt """ set_start_words = [set(x) for x in startWords] set_target_words = [set(x) for x in targetWords] result_cnt = 0
for i inrange(len(targetWords)): for j inrange(len(startWords)): iflen(targetWords[i]) - len(startWords[j]) != 1: continue iflen(list(set_target_words[i].symmetric_difference(set_start_words[j]))) == 1: print(set_target_words[i], set_start_words[j]) result_cnt += 1 break return result_cnt
修改后的不超时代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): defwordCount(self, startWords, targetWords): """ :type startWords: List[str] :type targetWords: List[str] :rtype: int """ set_start_words = set(["".join(sorted(list(startWord))) for startWord in startWords]) sorted_target_words = ["".join(sorted(list(targetWord))) for targetWord in targetWords] counter_sorted_target_words = Counter(sorted_target_words)
cnt = 0 for targetWord, value in counter_sorted_target_words.items(): for i inrange(len(targetWord)): tmp_s = targetWord[:i] + targetWord[i+1:] if tmp_s in set_start_words: cnt += value break return cnt