Quick Start Python
[2]:
import IPython; IPython.display.HTML('''<script>code_show=true; function code_toggle() { if (code_show){ $('div.nbinput').show(); } else { $('div.nbinput').hide(); } code_show = !code_show} $( document ).ready(code_toggle);</script><form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''')
[2]:
28. Implement strStr()
Easy
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Constraints:
0 <= haystack.length, needle.length <= 5 * 10^4
haystack and needle consist of only lower-case English characters.
[4]:
haystack = "hello"
needle = "ll"
def strStr(haystack, needle):
try:
return haystack.index(needle)
except ValueError:
return -1
strStr(haystack, needle)
[4]:
2
78. Subsets
Medium
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
All the numbers of nums are unique.
[1]:
# bottom up
nums = [1, 2, 3]
def subsets(nums):
res = [[]]
for n in nums:
for subset in res[:]:
res.append(subset + [n])
return res
subsets(nums)
[1]:
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]