题目

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。

示例 1:

输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:

输入: haystack = "aaaaa", needle = "bba"
输出: -1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

两种解法。

第一种:暴力直接求解,时间复杂度是O(n^2)。

第二种:Rabin-Karp算法。

时间复杂度O(m + n)。

代码

代码1

class Solution {
public int strStr(String haystack, String needle) {
if(haystack == null || needle == null) return -1;
for(int i=0; i < haystack.length() - needle.length() + 1; i++){
int j = 0;
for(; j < needle.length(); j++){
if(haystack.charAt(i + j) != needle.charAt(j)) break;
}
if(j == needle.length()) return i;
}
return -1;
}
}

代码2

class Solution {
static final int BASE = 1000000;
public int strStr(String haystack, String needle) {
if(haystack == null || needle == null) return -1;
if(needle.length() == 0) return 0; int m = needle.length();
//31 ^ m
int power = 1;
for (int i = 0; i < m; i++) {
power = (power * 31) % BASE;
} int targetCode = 0;
for (int i = 0; i < m; i++) {
targetCode = (targetCode * 31 + needle.charAt(i)) % BASE;
} int hashCode = 0;
for (int i = 0; i < haystack.length(); i++) {
hashCode = (hashCode * 31 + haystack.charAt(i)) % BASE;
if(i < m - 1){
continue;
} //减去开始的数 abcd - a
if(i >= m) {
hashCode = hashCode - (haystack.charAt(i - m) * power) % BASE;
if(hashCode < 0){
hashCode += BASE;
}
} //双重校验
if(hashCode == targetCode){
if(haystack.substring(i - m + 1, i + 1).equals(needle)){
return i - m + 1;
}
}
} return -1;
}
}

最新文章

  1. Building OpenCascade on Windows with Visual Studio
  2. MVC5 网站开发实践 2、后台管理
  3. 1Z0-053 争议题目解析607
  4. Java使用Mysql数据库实现批量添加数据
  5. 跟我一起学WCF(12)——WCF中Rest服务入门
  6. python解无忧公主的数学时间编程题001.py
  7. php会话(session)生命周期概念介绍及设置更改和回收
  8. Unity3D之如何创建正确的像素比在屏幕上
  9. layer弹出层不居中解决方案,layer提示不屏幕居中解决方法,layer弹窗不居中解决方案
  10. MVC5-Scaffolder
  11. CentOS上安装FastDFS分布式文件系统
  12. KMP快速模式匹配的java实现
  13. JAVA编译中拒绝访问的问题及解决方案
  14. hdu 6059---Kanade&#39;s trio(字典树)
  15. mysql5.6版本备份报错
  16. EF中关于TransactionScope的使用
  17. nginx 系列 1 linux下安装以及配置IIS分发
  18. js总结:三级联动
  19. python,异常处理
  20. 了解cron以及使用cron定时备份MySQL

热门文章

  1. Django模型层—ORM
  2. 字符串的扩展(ES6)
  3. springmvc源码学习
  4. 【Java必修课】好用的Arrays.asList也有这三个坑
  5. Python活力练习Day2
  6. HtEditor使用总结
  7. HA Joker Vulnhub Walkthrough
  8. Dynamic Code Evaluation:Unsafe Deserialization 动态代码评估:不安全反序列化
  9. 使用 ASP.NET Core MVC 创建 Web API(六)
  10. 基于canvas二次贝塞尔曲线绘制鲜花