1. 程式人生 > >Leetcode刷題記錄_20181027

Leetcode刷題記錄_20181027

next head rev num dict 元素 刷題記錄 als .com

205. Isomorphic Strings

判斷兩個字符串的是否同形。

利用字典,字符串中每一個不同的字符對應一個數字,最後數字相同則表示字符串同形。

更簡單的辦法:判斷len(set(s)) len(set(t)) len(set(zip(s,t))) 是否相等

技術分享圖片
 1 class Solution(object):
 2     def isIsomorphic(self, s, t):
 3         """
 4         :type s: str
 5         :type t: str
 6         :rtype: bool
 7         """
8 dict1 = {} 9 dict2 = {} 10 k =1 11 for i in s: 12 if i not in dict1: 13 dict1[i] = k 14 k +=1 15 k = 1 16 for i in t: 17 if i not in dict2: 18 dict2[i] = k 19 k +=1 20
list1 = [] 21 list2 = [] 22 for i in s: 23 list1.append(dict1[i]) 24 for i in t: 25 list2.append(dict2[i]) 26 return list1 == list2 27
View Code

206. Reverse Linked List

將鏈表翻轉。

技術分享圖片
 1 class Solution(object):
 2     def reverseList(self, head):
3 """ 4 :type head: ListNode 5 :rtype: ListNode 6 """ 7 a = head 8 temp1 = None 9 temp2 = None 10 while a: 11 temp2 = a.next 12 a.next = temp1 13 temp1 = a 14 a = temp2 15 return temp1
View Code

217. Contains Duplicate

判斷列表中是否存在相同數字

創建字典,在II問題中也可使用

219.Contains Duplicate II

判斷列表中相同數字的索引差值不大於給定整數k。

遍歷列表,建立列表元素與索引的字典,如有相同,判斷差值是否小於k。

技術分享圖片
 1 class Solution(object):
 2     def containsNearbyDuplicate(self, nums, k):
 3         """
 4         :type nums: List[int]
 5         :type k: int
 6         :rtype: bool
 7         """
 8         #超時方法,不可用
 9         """n = len(nums)
10         i = 0 
11         for j in range(k):
12             while i+j+1 < n:
13                 if nums[i] == nums[i+j+1]:
14                     return True
15                 else:
16                     i +=1
17             i = 0
18         return False"""
19         dict1 = {}
20         for i in range(len(nums)):
21             if nums[i] in dict1:
22                 if i - dict1[nums[i]] <= k:
23                     return True
24                 else:
25                     dict1[nums[i]] = i
26             else:
27                 dict1[nums[i]] = i
28         return False
View Code

Leetcode刷題記錄_20181027