28. Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
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().
Solution in C++:
关键点:情况考虑全面
int strStr(string haystack, string needle) {
if (needle.size() == 0) // 空指针
return 0;
size_t hSize = haystack.size();
size_t nSize = needle.size();
size_t i = 0, j = 0, lenth = 0;
bool flag = false;
if (nSize > hSize) // 子串比父串更长
return -1;
while(i < hSize && j < nSize){
if (haystack[i] == needle[j]){
flag = true;
lenth = j;
++i;
++j;
} else{
if (flag) // 之前有匹配的时候跳回开始之后的位置
i = i - lenth;
else
++i; // 没有匹配直接向后
flag = false;
j = 0;
}
}
if ( flag && j == nSize ) //
return (i-nSize);
else
return -1;
}
35. Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
Solution in C++:
int searchInsert(vector<int>& nums, int target) {
size_t size = nums.size(), i = 0;
for (; i < size; ++i){
if (nums[i] >= target)
return i;
}
return i;
}
小结
1.逻辑思维能力还需要再练习一下
第一个是字符串的模式匹配问题,由于没有记忆算法,所以直接自己写了一个暴力的,中间还存在一些考虑情况不全的时候,提交好几遍才AC。日后对字符串的模式匹配写篇博客,链接再放上去吧。
2.第二题很easy,但是还存在漏掉忘了在for循环之后还要return i。