实现 strStr()

题目描述:实现 strStr() 函数。

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

示例说明请见LeetCode官网。

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/implement-strstr/

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:穷举法
  • 首先,如果needle为空,直接返回0;如果 haystack 为空 或者 haystack 的长度 小于 needle 的长度,直接返回-1;
  • 否则,从 haystack 的第一位开始跟 needle 进行匹配,如果匹配不上,则往后继续遍历haystack,直到遍历完成,就能得到结果。

说明:该方法效率比较差。

解法二:KMP算法

首先,构造一个next数组,先计算出下一次跳转的位置,然后遍历按照next数组的位置将原串和匹配串进行匹配。

import com.google.common.base.Strings;

public class LeetCode_028 {
/**
* 穷举法
*
* @param haystack
* @param needle
* @return
*/
public static int strStr(String haystack, String needle) {
if (needle == null || needle.length() == 0) {
return 0;
}
if (haystack == null || haystack.length() == 0 || haystack.length() < needle.length()) {
return -1;
}
int first = 0;
while (first < haystack.length()) {
int matchCount = 0;
for (int i = 0; i < needle.length() && (i + first) < haystack.length(); i++) {
if (needle.charAt(i) == haystack.charAt(i + first)) {
matchCount++;
} else {
break;
}
}
if (matchCount == needle.length()) {
return first;
} else {
first++;
}
}
return -1;
} /**
* KMP算法
*
* @param haystack 原串
* @param needle 匹配串
* @return
*/
public static int strStr2(String haystack, String needle) {
if (Strings.isNullOrEmpty(needle)) {
return 0;
}
// 分别获取原串和匹配串的长度
int haystackLength = haystack.length(), needleLength = needle.length();
// 原串和匹配串前面都加一个空格,使其下标从1开始
haystack = " " + haystack;
needle = " " + needle; char[] haystackList = haystack.toCharArray();
char[] needleList = needle.toCharArray(); // 构建 next 数组,数组长度为匹配串的长度(next 数组是和匹配串相关的)
int[] next = new int[needleLength + 1];
// 构造过程 i = 2, j = 0 开始,i 小于等于匹配串长度【构造 i 从 2 开始】
for (int i = 2, j = 0; i <= needleLength; i++) {
// 匹配不成功的话,j = next[j]
while (j > 0 && needleList[i] != needleList[j + 1]) {
j = next[j];
}
// 匹配成功的话,先让 j++
if (needleList[i] == needleList[j + 1]) {
j++;
}
// 更新 next[i],结束本次循环, i++
next[i] = j;
} // 匹配过程,i = 1, j = 0 开始,i 小于等于原串长度【匹配 i 从 1 开始】
for (int i = 1, j = 0; i <= haystackLength; i++) {
// 匹配不成功 j = next[j]
while (j > 0 && haystackList[i] != needleList[j + 1]) {
j = next[j];
}
// 匹配成功的话,先让 j++,结束本次循环后 i++
if (haystackList[i] == needleList[j + 1]) {
j++;
}
// 整一段都匹配成功,直接返回下标
if (j == needleLength) {
return i - needleLength;
}
} return -1;
} public static void main(String[] args) {
System.out.println(strStr("mississippi", "issi")); System.out.println(strStr2("mississippi", "issi"));
}
}

【每日寄语】 在最美的年华,做最喜欢的事情,别辜负了美好时光,借时光之手,暖一处花开,借一方晴空,拥抱梦想。

LeetCode-028-实现 strStr()的更多相关文章

  1. Java for LeetCode 028 Implement strStr()

    Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle ...

  2. LeetCode 028 Implement strStr()

    题目要求:Implement strStr() Implement strStr(). Returns the index of the first occurrence of needle in h ...

  3. 前端与算法 leetcode 28.实现 strStr()

    # 前端与算法 leetcode 28.实现 strStr() 题目描述 28.移除元素 概要 这道题的意义是实现一个api,不是调api,尽管很多时候api的速度比我们写的快(今天这个我们可以做到和 ...

  4. 【LeetCode】028. Implement strStr()

    Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle ...

  5. LeetCode 28 Implement strStr() (实现找子串函数)

    题目链接: https://leetcode.com/problems/implement-strstr/?tab=Description   Problem : 实现找子串的操作:如果没有找到则返回 ...

  6. 028 Implement strStr() 实现 strStr()

    实现 strStr().返回蕴含在 haystack 中的 needle 的第一个字符的索引,如果 needle 不是 haystack 的一部分则返回 -1 .例 1:输入: haystack = ...

  7. 【LeetCode】Implement strStr()(实现strStr())

    这道题是LeetCode里的第28道题. 题目描述: 实现 strStr() 函数. 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle ...

  8. [LeetCode] 28. Implement strStr() 实现strStr()函数

    Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle ...

  9. Java实现 LeetCode 28 实现strStr()

    28. 实现 strStr() 实现 strStr() 函数. 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 ...

  10. [leetcode 27]Implement strStr()

    1 题目: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if ...

随机推荐

  1. Vue 之 浏览本地图片功能

      template <input type="file" ref="input_file" @change="fileChange" ...

  2. CF1408G Clusterization Counting

    首先,我们需要给一个连通块找到一个直观的合法判定解. 那么我们必须以一种直观的方式将边按照权值分开,这样才能直观地判定一个合法的组. 一个常见的方式是将边从小到大依次加入进来,那么在任意时刻图上存在的 ...

  3. java-swing-事件监听-焦点监听器

    感谢大佬:https://blog.csdn.net/weixin_44512194/article/details/93377551 开始不知道焦点是啥,其实就是打字的时候,这个一闪一闪的竖线. 与 ...

  4. StringUtils.isBlank(str)和StringUtils.isEmpty(str)的区别

    1.StringUtils.isEmpty(CharSequence cs)实现源码 public static boolean isEmpty(CharSequence cs) { return c ...

  5. opcache,opcode,apc和apcu的区别

    opcode opcode是php解析器生成的操作码,类似java的字节码,main.class文件. opcache opcache是php的扩展,是一个实现将PHP字节码(OPCode)缓存到共享 ...

  6. Java线程--CyclicBarrier使用

    原创:转载需注明原创地址 https://www.cnblogs.com/fanerwei222/p/11867687.html Java线程--CyclicBarrier使用, 代码里头有详细注释: ...

  7. php函数(parse_str()

    parse_str()函数 把查询字符串解析到变量中 parse_str(string, array); string 规定要解析的字符串 array 存储变量的数组名称 例子: <?php p ...

  8. TCP的报文详细解读

    这张图好像挺有名的,其实一开始我看见的时候是一脸懵逼的,但是通过翻书(大学时代最害怕的计算机网络),查阅他人博客等等办法,最后终于有了一个系统的了解,当然,这里知识点多而杂,大家可以多看几遍,结合上面 ...

  9. appium填坑

    首次使用appium web driver,不说搭建环境的麻烦,初次写完一个操作计算器的程序,但是运行一直报错:selenium.common.exceptions.WebDriverExceptio ...

  10. ios plist获取权限

    最近太忙了,没有时间写vue 这个权限获取有点坑,极不好记,所以备份一份 <key>NSVideoSubscriberAccountUsageDescription</key> ...