当前位置: 首页 > news >正文

LeetCode每日一题(28. Find the Index of the First Occurrence in a String)

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = “sadbutsad”, needle = “sad”
Output: 0

Explanation: “sad” occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.

Example 2:

Input: haystack = “leetcode”, needle = “leeto”
Output: -1

Explanation: “leeto” did not occur in “leetcode”, so we return -1.

Constraints:

  • 1 <= haystack.length, needle.length <= 104
  • haystack and needle consist of only lowercase English characters.

用 Rabin-Karp 算法



impl Solution {pub fn str_str(haystack: String, needle: String) -> i32 {let needle_hash = needle.chars().fold(0, |mut h, c| {h *= 256;h += c as i32;h %= 101;h});let power = (1..needle.len()).fold(1, |mut p, _| {p *= 256;p %= 101;p});let mut haystack_hash = 0;let mut queue = Vec::new();for (i, c) in haystack.chars().enumerate() {if queue.len() == needle.len() {haystack_hash += 101;haystack_hash -= queue.remove(0) as i32 * power % 101;}haystack_hash *= 256;haystack_hash += c as i32;haystack_hash %= 101;queue.push(c);if queue.len() == needle.len() && needle_hash == haystack_hash && haystack[i + 1 - needle.len()..i + 1] == needle[..] {return (i + 1 - needle.len()) as i32;}}-1}
}
http://www.lryc.cn/news/27807.html

相关文章:

  • Android 圆弧形 SeekBar
  • java 字典
  • 【企业服务器LNMP环境搭建】mysql安装
  • vue自定义指令以及angular自定义指令(以禁止输入空格为例)
  • 异常 复习
  • K8s:开源安全平台 kubescape 实现 Pod 的安全合规检查/镜像漏洞扫描
  • C#中,FTP同步或异步读取大量文件
  • STM32单片机的FLASH和RAM
  • Java 二叉树的遍历
  • 实习日记-C#
  • Tech Lead如何引导团队成员解决问题?
  • 07--组件
  • 怎么做好一个完整的项目复盘
  • 浅谈一下mysql8.0与5.7的字符集
  • paddle推理部署(cpu)
  • 想开发IM集群?先搞懂什么是RPC!
  • 案例13-前端对localStorage的使用分析
  • CNNIC第51次中国互联网络发展状况统计报告用户规模变化发布、解读与白杨SEO看法
  • 【数据结构】单链表的实现
  • 从0到1做产品!产品设计的6个步骤
  • ESP32遥控器软硬件设计
  • vue-template-admin的keep-alive缓存与移除缓存
  • 【人工智能 AI】机器学习快速入门教程(Google)
  • 适配器模式
  • 00后跨专业学软件测试,斩获8.5K高薪逆袭职场
  • 数据结构和算法学习
  • 剑指 Offer II 012. 左右两边子数组的和相等
  • Java货物摆放
  • 计算机求解满足三角形各边数字之和相等的数字填充
  • python魔术方法