Quick Start C++
[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.
[26]:
// std::string 有 .c_str() 可以轉成 const char *
#include <cstring>
#include <string>
int strStr(std::string haystack, std::string needle)
{
const char* ptr = std::strstr(haystack.c_str(), needle.c_str());
return ptr ? (long)(ptr - haystack.c_str()) : -1;
}
const char* haystack = "hello";
const char* needle = "ll";
strStr(haystack, needle)
[26]:
2
[5]:
// LeetCode 上的 readable solution
#include <cstring>
#include <string>
int strStr(std::string haystack, std::string needle) {
if(needle.size() == 0)
return 0;
int len = haystack.length() - needle.length();
for(int i=0 ; i<=len ; i++) {
if(haystack.substr(i, needle.length()) == needle)
return i;
}
return -1;
}
const char* haystack = "hello";
const char* needle = "ll";
strStr(haystack, needle)
[5]:
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.
[2]:
// bottom up
#include <vector>
#include <iostream>
auto subsets(std::vector<int>& nums) {
std::vector<std::vector<int>> res = {{}};
for(const int n : nums)
{
std::vector<std::vector<int>> cur_res = res;
for(std::vector<int> subset : cur_res)
{
subset.push_back(n);
res.push_back(subset);
}
}
return res;
}
std::vector<int> nums = {1, 2, 3};
subsets(nums)
[2]:
{ {}, { 1 }, { 2 }, { 1, 2 }, { 3 }, { 1, 3 }, { 2, 3 }, { 1, 2, 3 } }