Skip to content

Commit a7f4305

Browse files
committed
Copy List with Random Pointer/ Word Break
1 parent fccca5c commit a7f4305

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
'''
2+
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
3+
4+
Return a deep copy of the list.
5+
'''
6+
7+
# Definition for singly-linked list with a random pointer.
8+
class RandomListNode(object):
9+
def __init__(self, x):
10+
self.label = x
11+
self.next = None
12+
self.random = None
13+
14+
15+
class Solution(object):
16+
def copyRandomList(self, head):
17+
"""
18+
:type head: RandomListNode
19+
:rtype: RandomListNode
20+
"""
21+
if not head:
22+
return None
23+
visited = dict()
24+
node = head
25+
while node:
26+
visited[node] = RandomListNode(node.label)
27+
node = node.next
28+
29+
visited[None] = None
30+
node = head
31+
while node:
32+
visited[node].next = visited[node.next]
33+
visited[node].random = visited[node.random]
34+
node = node.next
35+
return visited[head]
36+
37+
38+
if __name__ == "__main__":
39+
None

139 Word Break.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
'''
2+
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
3+
4+
For example, given
5+
s = "leetcode",
6+
dict = ["leet", "code"].
7+
8+
Return true because "leetcode" can be segmented as "leet code".
9+
'''
10+
11+
class Solution(object):
12+
def wordBreak(self, s, wordDict):
13+
"""
14+
:type s: str
15+
:type wordDict: Set[str]
16+
:rtype: bool
17+
"""
18+
n = len(s)
19+
dp = [False] * (n + 1)
20+
dp[0] = True
21+
for i in range(n):
22+
for j in range(i, -1, -1):
23+
if dp[j] and s[j:i + 1] in wordDict:
24+
dp[i + 1] = True
25+
break
26+
return dp[n]
27+
28+
29+
if __name__ == "__main__":
30+
assert Solution().wordBreak("leetcode", {"leet", "code"}) == True

0 commit comments

Comments
 (0)