描述
对于一个给定的 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
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?