描述
对于一个给定的 source
字符串和一个 target
字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0
开始)。如果不存在,则返回 -1
。
如: 查找 "abcdef" 中是否存在 "cde".
LintCode 领扣Powerful coding training system. LintCode has the most interview problems covering Google, Facebook, Linkedin, Amazon, Microsoft and so on. We provide Chinese and English versions for coders around the world.https://www.lintcode.com/problem/13/
class Solution {
public:
/**
* @param source:
* @param target:
* @return: return the index
*/
//面试点: 简单题, 看候选人的基本功,不要求写出KMP, 但想看下候选人的coding能力在平均以上还是以下.
//考点: 代码风格- 空格的地方是否空格,换行的地方是否换行,空行的地方是否空行.
//思想: 外层遍历target, 内层遍历source, 注意遍历边界条件,判断相等条件, 终止条件.
int strStr(const string &source, const string &target) {
int sourceLen = (int)source.length(); //严谨: size_t即unsigned int 转 int
int targetLen = (int)target.length();
if (0 == targetLen) { //注意边界条件: 不能直接 if (target.empty() || source.empty())
return 0; //注意: 空字符串存在与任何字符串中,所以返回0
}
if (sourceLen < targetLen) {
return -1;
}
for (int i = 0; i
关注
打赏