版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BruceYan63/article/details/79144400
13. 字符串查找
题目来源:LintCode
题目:
对于一个给定的 source 字符串和一个 target字符串, 你应该在 source 字符串中找出 target 字符串
出现的第一个位置(从0开始), 如果不存在, 则返回 -1.
样例
如果 source = "source" 和 target = "target", 返回 -1
如果 source = "abcdabcdefg" 和 target = "bcd", 返回 1
难度级别:
容易
容易
使用的编程语言:
C++
思路分析:
看到题目马上提炼出问题的核心:找子串的索引. 马上想到 String类自带函数里的find()方法刚好能做到这一点,
假如没找到子串, 就会返回-1, 与题意吻合.所以直接将传入的字符数组转成字符串, 直接进行操作, 非常简便
实现代码:
class Solution {
public:
/*
* @param source: source string to be scanned.
* @param target: target string containing the sequence of characters to match
* @return: a index to the first occurrence of target in source, or -1 if target is not part of source.
*/
int strStr(const char *source, const char *target) {
int index = 0;
if (source == NULL || target == NULL)
{
index = -1;
return index;
}
string t = (target);
string s = (source);
/*char* temp = new char[100];
strncpy(temp, target, target.length());*/
index = s.find(t);
return index;
}
};
14. 二分查找
题目来源:LintCode
题目:
给定一个排序的整数数组(升序) 和一个要查找的整数 target, 用O(logn)的时间查找到target第一次出现的下标(从0开始),
如果 target不存在于数组中, 返回 -1.
样例
在数组 [1, 2, 3, 3, 4, 5, 10]中二分查找3, 返回2.
难度级别:
中等
中等
使用的编程语言:
C++
思路分析:
我花在这道题上的时间比上一道多了十几倍, 虽然利用二分查找法找索引是没有什么难度,
但就在找最小索引处卡住, 随后我用了一种"奇葩"方法, 希望以后随着题量增多能有所改观.
实现代码:
int binarySearch(vector<int> &array, int target)
{
int counter = 0, temp = 0, mid = 0;
int low = 0, high = array.size();
while (low <= high)
{
mid = (low+high)/2;
if (array[mid] == target)
{
counter++;
//寻找最小索引
for (int i = mid; i >= low; i--)
{
if (array[i] == target)
{
temp = i;
}
}
return temp;
}
else if (array[mid] > target)
{
high = mid-1;
}
else
{
low = mid+1;
}
}
return -1;
}
};