LeetCode 28. Implement strStr()

光模块封装工艺简介 光模块按照部件可以分为芯片、光器件、光模块三个层级;按照应用领域大概可分为电信应用、数通应用两个领域;按照内部器件的封装工艺可分为TO、Box、COB三大类。 但是,无论是哪种类型的光模块,其生产工艺基本上可以分为封装、测试两大块。   那什么叫做器件封装呢?我的理解器件封装就是利用胶水、焊料、机械、热量等手段把器件按照一定的先后次序结合形成一个整体的过程,就好像早上吃的煎饼,把面粉、鸡蛋、脆饼、烤肠、葱花等这些“器件”,按照一定的顺序,通过食用油、甜面酱、加热、卷起来等手段结合到一起,形成了美味的 阅读详情

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.


It is pretty hard to generalize KMP algorithm under stress and limited time. Better to formalize brute force first and then move forward to KMP.

#include <string>
#include <iostream>
#include <vector>
using namespace std;

// brute force
int strStr(string haystack, string needle) {
    int m = haystack.size();
    int n = needle.size();
    int i = 0, j = 0;
    while(i < m && j < n) {
        if(haystack[i] == needle[j]) {
            i++;
            j++;
        } else {
            i = i - j + 1;
            j = 0;
        }
    }
    return j == n ? i - j : -1;
} // time complexity: O(m*n)


// KMP to make the time complexity to be O(m + n);
vector<int> next(string& needle) {
    vector<int> next(needle.size(), 0);
    for(int i = 1; i < needle.size(); ++i) {
        int j = next[i-1];
        while(j > 0 && (needle[i] != needle[j])) j = next[j-1];
        next[i] = (j + (needle[i] == needle[j]));
    }
    return next;
}

int strStrII(string haystack, string needle) {
    vector<int> nextV = next(needle);
    int k = 0;
    for(int i = 0; i < haystack.size(); ++i) {
        while(k > 0 && haystack[i] != needle[k]) k = nextV[k-1];
        if(haystack[i] == needle[k]) k++;
        if(k == needle.size()) return i - needle.size() + 1;
    }
    return -1;
}

One Variation in Facebook interview.

/*
  StrStr variation.
  implement function strstr(string a, string b) return index where any permutation
  of b is a substring of a.
  eg:
  strstr("hello", "ell") return 1
  strstr("hello", "lle") return 1
  strstr("hello", "wor") return -1;
*/
void permutate(string target, string path, set<string>& res) {
  if(target.size() == 0) {
    res.insert(path);
    return;
  }
  for(int i = 0; i < target.size(); ++i) {
    string remains = target.substr(0, i) + target.substr(i + 1);
    permutate(remains, path + target[i], res);
  }
}
set<string> permutate(string target) {
  string path = "";
  set<string> res;
  permutate(target, path, res);
  return res;
}

int strstr(string orig, string target) {
  set<string> perm = permutate(target);
  auto iter = perm.begin();
  int k = target.size();
  for(int i = 0; i < orig.size() - k; ++i) {
    string tmp = orig.substr(i, k);
    if(perm.find(tmp) != perm.end()) return i;
  }
  return -1;
}

int main(void) {
  cout << strstr("hello", "ell") << endl;
  cout << strstr("hello", "lle") << endl;
  cout << strstr("hello", "wor") << endl;
}

Facebook has a variation related question: 两个string,如果第二个在第一个里没有出现return-1,如果出现了return最后一次出现时候在第一个string里的position

This is a variation to KMP algorithm. We just need to reverse the str and the pattern, apply KMP. The tricky part is to find the right index.


Another variation:

Suppose the given haystack is a matrix, the pattern string is a normal string. Return the start index otherwise return -1

#include "header.h"
using namespace std;

// strstr follow up. The input string is a 2D array.
/*
  For example,
Give:
  [[a, b, c, c]
   [c, b, d, e]
  ]
Needle: [c, c, b, d] return 2.
Needle: [b, d] return 5.
*/
vector<int> getPrefix(string pattern) {
  int n = pattern.size();
  vector<int> next(n, 0);
  int i = 1, j = 0;
  while(i < n) {
    j = next[i-1];
    while(j > 0 && (pattern[i] != pattern[j])) j = next[j-1];
    next[i] = (j + pattern[i] == pattern[j]);
    i++;
  }
  return next;
}

char getMatrixChar(vector< vector<char> >& matrix, int i) {
  int cols = matrix[0].size();
  return matrix[i / cols][i % cols];
}
int findTargetInMatrix(vector< vector<char> >& matrix, string pattern) {
  int rows = matrix.size();
  int cols = matrix[0].size();
  int i = 0, j = 0;
  vector<int> next = getPrefix(pattern);
  while(i < rows*cols) {
    char tmp = getMatrixChar(matrix, i);
    while(j > 0 && (tmp != pattern[j])) j = next[j-1];
    if(tmp == pattern[j]) {j++;}
    i++;
    if(j == pattern.size()) return i - pattern.size();
  }
  return -1;
}


int main(void) {
  vector< vector<char> > matrix {
    {'a', 'b', 'c', 'c'},
    {'c', 'b', 'd', 'e'}};
  cout << findTargetInMatrix(matrix, "cccb") << endl;
}

Open3D 进阶(22)间接平差法拟合空间曲线 空间曲线拟合在电力线三维重建中有着广泛的应用,本文利用python使用间接平差法对三维空间曲线的拟合进行代码实现。 阅读详情

相关推荐

STM32CubeIDE入坑指南

一 前言 在科技日新月异的今天,作为从事效率为先的苦逼 IT 行业,秉承着我不入地狱谁入地狱的伟大革命精神,我决定再一次做第一个吃螃蟹的人,通过自身的入坑过程,为大家测试STM32CubeIDE这款新式工具。(其实是为了我能省点时间,快点做完项目,多挣点钱买几瓶肾气丸) 二 看一看别人是如何入坑的 二 手把手带你入坑 三 相关资料 ...

CH的博客 1万+

[28] Implement strStr()

给定两个字符串,判断一个字符串是不是另一个字符串的子串,如果是返回第一个字串位置,如果不是返回-1。

camlot的博客 1667

ADC INL&DNL测试方法和实例

本文介绍了一种可操作的ADC INL和DNL的测试方法--直方图法(也称码密度法)。并实际使用该方法测试了两款芯片的ADC INL和DNL

APTCHIP的博客 1万+

28. Implement strStr() [easy] (Python)

题目链接https://leetcode.com/problems/implement-strstr/题目原文 Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 题目翻译实现 strSt

Coder_Orz的博客 7943

使用Java实现CRC16 MODBUS 格式校验

CRC16校验,测试如下 String str = "a5 98 03 00 00 5f c6 0f 7c 40 78 06 09 46 dc 6e db 00 16 3e 12 5c 98 00 19 98 0e 10 03 06 09 46 dc 6e db 03 0b bf 5f c6 0f 7c 43 bd b9 61 ee 96 76 99"; 校验规则: /** * CRC16_CCITT:多项式x16+x12+x5+1(0x1021),初始值0x0000,低位在前,高位在后,结

weixin_45063710的博客 1312

TwinCAT 3 实战:手把手教你用PLC和C++读写第三方伺服驱动器的CoE参数

本文详细介绍了在TwinCAT 3环境中通过PLC和C++两种技术路线实现对第三方伺服驱动器CoE参数的精准操控。从环境准备到具体实现,包括硬件配置、核心函数使用及性能优化策略,为工程师提供了全面的实战指南。特别针对CoE参数访问的效率和稳定性问题,给出了实用的调试技巧和异常处理方案。

weixin_33743248的博客 442

【一天一道LeetCode】#28. Implement strStr()

一天一道LeetCode系列(一)题目 Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. (二)解题第一种解法:朴素匹配算法 /*两个指针,分别指向两个字符串的首字符如果相等则一起向后移

ZeeCoder 3787

Proxmox PVE 黑苹果安装全攻略:从镜像准备到系统配置

本文提供了一份在Proxmox PVE虚拟化平台上安装macOS(黑苹果)的详细指南。内容涵盖从获取OpenCore引导镜像和macOS安装镜像、宿主机环境检查与调优,到创建虚拟机、修改关键配置文件、解决引导问题以及安装后优化的全流程。重点在于通过正确的PVE配置和参数调整,成功在KVM虚拟机中运行macOS系统,为开发测试提供灵活环境。

opencv7vision的博客 1107

28. Implement strStr()

子串查找问题:在haystack中查找needle第一次出现的索引,如果needle不是haystack的一部分,则返回-1 子串匹配问题在数据结构(C语言版)(严蔚敏、吴伟民)这本书里面已经讲得很详细了,包括暴力求解法、KMP算法、改进的KMP算法等。 在刷题的时候,怀着侥幸的心理首先尝试了一下暴力求解法。然而,通过了!!!而且打败了47.65%的提交者,于是乎没有尝试KMP

清风徐来,水波不兴 385

R语言实战应用精讲50篇(二)-多重线性回归系列之稳健回归

前言 线性回归的参数估计主要采用的是最小二乘法(又称最小平方法),该法是将使观测值与模型预测值之差的平方达到最小的值作为参数估计值。如果数据存在异常点或者异方差,最小二乘法估计会存在偏差,常用的处理策略就是改用稳健回归(Robust Regression)。 稳健回归就是采用更为稳健的参数估计方法来拟合模型,所谓稳健就是数据的波动对参数估计影响不大,比如不受异常值影响,或删除某一观测后对结果影响不大。稳健估计的方法有很多,主要有这么几类:最小绝对值回归(也称最小一乘法回归,lAV),最小中位数二乘法(L

wenyusuran的专栏 3160

在 SAP Fiori 中正确配置 Group 角色:从 PFCG 分配到首页呈现的完整链路

摘要:SAP Fiori项目中,用户登录后能否看到应用往往取决于角色配置而非前端开发。关键在于通过PFCG角色将launchpad designer中创建的tile group关联到用户角色。Catalog是应用池,group是用户首页可见的工作区。正确配置后,用户会看到角色对应的默认分组,同时保留个性化调整能力。项目实施中常见问题是应用开发完成但未正确配置group与角色关联,导致业务用户无法在首页看到应用入口。(150字)

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 164

28. Implement strStr()-leetcode-java

【原来在SAE的blog上,都转到优快云了。。】 28. Implement strStr()-leetcode-java 发表于 2016/02/06 题意 Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if

you are what you read 1927

uniapp [全端兼容] - 详细实现下拉筛选菜单功能组件,下拉式筛选菜单效果,类似电商美团点击筛选项底部弹出列表点击选择后自动收起(详细示例代码,全端兼容小程序、安卓苹果app、h5网页、nvue

uni-app,vue2,vue3,向下弹出菜单包含筛选功能,日期筛选,下拉框选择器,下拉多条件筛选,下拉式筛选菜单,uniApp如何实现条件下拉筛选,Uniapp官方条件筛选组件,下拉框式条件筛选插件组件,最好用的插件组件,多端兼容,下拉菜单筛选,过滤筛选列表,下拉筛选栏,多列联动的条件筛选,下拉菜单地区和筛选,微信小程序,支付宝小程序,h5网页,移动端网站,安卓app,苹果app,nvue,uniapp所有平台兼容,下拉菜单筛选,下拉式条件筛选,下拉列表,点击排序,级联筛选,uniapp实现下拉筛选

🏆 前端领域优质创作者 1万+

LeetCode力扣 28. 实现 strStr() Implement strStr() 题解代码 JavaScript

问题https://leetcode-cn.com/problems/implement-strstr/ 练习使用JavaScript解答 /** * @param {string} haystack * @param {string} needle * @return {number} */ var strStr = function(haystack, needle) { return haystack.indexOf(needle); }; 题目是让实现,直接用库好像不太合适.

Coding home - 漂流瓶jz 513

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

Leetcode 28. Implement strStr() 实现 strStr()

@[TOC](Leetcode 28. Implement strStr() 实现 strStr()) 28. Implement strStr() 题目描述 Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of hayst...

importsys的博客 291

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

LeetCode OJ 28 Implement strStr() [Easy]

LeetCode OJ 28  Implement strStr()   题目描述: Implement strStr(). Returns the index of the first occurrenceof needle in haystack, or -1 if needle is not part of haystack. 题目理解: 给定两个字符串haystack和ne

大吱的博客 283

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Leetcode 28. Implement strStr()

class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ return haystack.find(...

weixin_30662109的博客 83

LeetCode 28. Implement strStr() 题解

本题是字符串匹配的经典问题,主要考察对字符串处理和 KMP 算法的理解和应用。通过使用暴力解法或 KMP 算法,我们可以高效地实现strStr()函数。暴力解法的核心思想是:遍历 haystack 字符串,对于每个位置,检查从该位置开始的子字符串是否与 needle 相等。KMP 算法的核心思想是:通过构建前缀函数,在匹配失败时快速回退,避免重复比较。在实际应用中,KMP 算法通常更受欢迎,因为它的时间复杂度更低,尤其是在处理长字符串时。这种方法不仅适用于实现strStr()

cannonjinx的博客 4293

【LEETCODE】28-Implement strStr()

Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 参考: http://blog.csdn.net/hcbbt/article/details/44099749 http://w

aliceyangxi1987的博客 624

leetcode刷题记录-28. Implement strStr()

leetcode刷题记录-28. Implement strStr() 1.题目要求   Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.   Example 1:   Input: haystack = “hello”, ne...

zhaizhan501的博客 207

Leetcode学习笔记:#28. Implement strStr()

Leetcode学习笔记:#28. Implement strStr() Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 实现: public int strStr(String haystack,...

ccystewart的博客 152

LeetCode 28. 实现 strStr() Implement strStr()

Table of Contents 一、中文版 二、英文版 三、My answer 四、解题报告 一、中文版 实现strStr()函数。 给定一个haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回-1。 示例 1: 输入: haystack = "hello", needle = "ll" 输出: 2 示例 2: 输入: haystack = "aaaaa", need...

三妹的博客 223

Leetcode 28. Implement strStr() 实现strStr()

Leetcode 28. Implement strStr() 实现strStr() 标签: Leetcode 题目地址:https://leetcode-cn.com/problems/implement-strstr/ 题目描述 实现&nbsp;strStr()&nbsp;函数。 给定一个&nbsp;haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 n...

CoderWangSon 163

LeetCode【#28】Implement strStr()

题目链接: 点击跳转 题目: ImplementstrStr(). Return the index of the first occurrence of needle in haystack, or-1if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "l...

Mikchy的博客 264

[LeetCode] 28. Implement strStr()

原题链接:

Ber03的博客 234
上一篇: LeetCode 81. Search in Rotated Sorted Array II
下一篇: LeetCode 173. Binary Search Tree Iterator
ActiveCoder
博客等级 码龄11年 4粉丝 345原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值