①实现strStr()
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:
当 needle
是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle
是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
1.常规思路,使用两层循环,外层遍历haystack,内层匹配needle,如果内层完全匹配,则返回匹配的位置:
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle == "")
return 0;
if (haystack.size() < needle.size())
return -1;
for (int i = 0; i < haystack.size(); ++i)
{
int j = 0;
for ( j = 0; j < needle.size(); ++j)
{
if (haystack[i + j] != needle[j]) //如果字符不相等,则进行haystack下一个字符判断
break;
}
if (j == needle.size()) //判断是否完全匹配
return i;
}
return -1; //如果经过上述判断未能得出结果,则说明needle字符串不在haystack中
}
};
2.省去了内层循环,使用substr复制与needle相同长度的字符串,用该字符串与needle比较:
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle == "")
return 0;
if (haystack.size() < needle.size())
return -1;
int ret = 0;
for (int i = 0; i < haystack.size(); ++i)
{
ret = i;
string s;
if (haystack.substr(i,needle.size()) == needle) //利用函数substr复制与needle字符串相同的字符串与needle比较,如果相等则返回当前下标
return ret;
}
return -1;
}
};
3.使用find算法在haystack字符串中查找是否存在needle字符串(一行):
class Solution {
public:
int strStr(string haystack, string needle) {
return haystack.find(needle);
}
};
②搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5
输出: 2
示例 2:
输入: [1,3,5,6], 2
输出: 1
示例 3:
输入: [1,3,5,6], 7
输出: 4
示例 4:
输入: [1,3,5,6], 0
输出: 0
1.直接for循环遍历查找,如找到比目标数值target大的数据,则返回当前数据的位置作为target的插入位置,如果未找到则插入到数组末尾位置:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int ret;
if (nums.empty()) return 0;
for (int i = 0; i < nums.size(); ++i)
{
ret = i;
if (nums[i] >= target)
return ret;
}
if (ret == nums.size() - 1)
return nums.size();
}
};