File tree Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ Reverse a linked list from position m to n. Do it in one-pass.
3
+
4
+ Note: 1 ≤ m ≤ n ≤ length of list.
5
+
6
+ Example:
7
+
8
+ Input: 1->2->3->4->5->NULL, m = 2, n = 4
9
+ Output: 1->4->3->2->5->NULL
10
+ '''
11
+
12
+ # Definition for singly-linked list.
13
+ # class ListNode(object):
14
+ # def __init__(self, x):
15
+ # self.val = x
16
+ # self.next = None
17
+
18
+ class Solution (object ):
19
+ def reverseBetween (self , head , m , n ):
20
+ """
21
+ :type head: ListNode
22
+ :type m: int
23
+ :type n: int
24
+ :rtype: ListNode
25
+ """
26
+ if m == n :
27
+ return head
28
+
29
+ result = ListNode (0 )
30
+ result .next = head
31
+
32
+ prev = result
33
+
34
+ for index in range (m - 1 ):
35
+ prev = prev .next
36
+
37
+ reverse = None
38
+ curr = prev .next
39
+ for i in range (n - m + 1 ):
40
+ temp = curr .next
41
+ curr .next = reverse
42
+ reverse = curr
43
+ curr = temp
44
+
45
+ prev .next .next = curr
46
+ prev .next = reverse
47
+ return result .next
Original file line number Diff line number Diff line change
1
+ '''
2
+ Given a string containing only digits, restore it by returning all possible valid IP address combinations.
3
+
4
+ Example:
5
+
6
+ Input: "25525511135"
7
+ Output: ["255.255.11.135", "255.255.111.35"]
8
+ '''
9
+
10
+ class Solution (object ):
11
+ def restoreIpAddresses (self , s ):
12
+ """
13
+ :type s: str
14
+ :rtype: List[str]
15
+ """
16
+ result = []
17
+
18
+ def dfs (s , temp , count ):
19
+ if count == 4 :
20
+ if not s :
21
+ result .append (temp [:- 1 ])
22
+ return
23
+
24
+ for index in range (1 , 4 ):
25
+ if index <= len (s ):
26
+ if index == 1 :
27
+ dfs (s [index :], temp + s [:index ] + "." , count + 1 )
28
+ elif index == 2 and s [0 ] != '0' :
29
+ dfs (s [index :], temp + s [:index ] + "." , count + 1 )
30
+ elif index == 3 and s [0 ] != '0' and int (s [:3 ]) <= 255 :
31
+ dfs (s [index :], temp + s [:index ] + "." , count + 1 )
32
+
33
+ dfs (s , "" , 0 )
34
+ return result
You can’t perform that action at this time.
0 commit comments