码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode刷题记录_20181027

时间:2018-10-27 23:35:54      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:style   遍历   https   type   .com   方法   color   使用   obj   

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

标签:style   遍历   https   type   .com   方法   color   使用   obj   

原文地址:https://www.cnblogs.com/autoyzz/p/9863817.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!