您当前的位置: 首页 >  面试

惊鸿一博

暂无认证

  • 5浏览

    0关注

    535博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

算法笔记_面试题_14. strStr 长字符串中查找短字符串

惊鸿一博 发布时间:2021-10-17 16:34:35 ,浏览量:5

描述

对于一个给定的 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             
关注
打赏
1663399408
查看更多评论
0.0472s