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

题目介绍

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

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

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

题解思路

题干很短,刚看完估计就已经有想法了,其实我第一个想到的是KMP算法

KMP算法是一种模式匹配算法,通过找到前后缀的办法来判断字符串的匹配

当我还在觉得有点复杂的代码的时候,官方题解还是简单明了,直接用String类中的substring方法截取等长字符串比较

其实自己用这个方法用的挺少的,大多数还是equals、charAt、getBytes、HashCode、indexof、length等

以后常用类的方法都要牢记,否则很多算法将很麻烦或者根本无从下手

官方还给了其他两种方法,一种是双指针的,也比较好理解,偏向暴力解法,最后一个实在没太明白,滚动哈希什么的确实没听过,果然还和大牛还有很大差距

正确代码

public int strStr(String haystack, String needle) {
	int h = haystack.length();
	int n = needle.length();
		
	for (int i = 0; i < h - n + 1; ++i) {
		//substring方法用于截取字符串
		if(haystack.substring(i,i+n).equals(needle)) {
			return i;
		}
	}
        return -1;
  }

//下面是官方的第二种解法,就直接拿来了
class Solution {
  public int strStr(String haystack, String needle) {
    int L = needle.length(), n = haystack.length();
    if (L == 0) return 0;

    int pn = 0;
    while (pn < n - L + 1) {
      // find the position of the first needle character
      // in the haystack string
      while (pn < n - L + 1 && haystack.charAt(pn) != needle.charAt(0)) ++pn;

      // compute the max match string
      int currLen = 0, pL = 0;
      while (pL < L && pn < n && haystack.charAt(pn) == needle.charAt(pL)) {
        ++pn;
        ++pL;
        ++currLen;
      }

      // if the whole needle string is found,
      // return its start position
      if (currLen == L) return pn - L;

      // otherwise, backtrack
      pn = pn - currLen + 1;
    }
    return -1;
  }
}

总结

其实算法的解决方式有很多种,最优的解法当然是不存在的,算法的优化是永远在进行的永恒话题

所以作为一名优秀的程序猿,(虽然自己现在可能只是个码农吧)掌握好扎实的基本知识和正确的逻辑思维是十分重要的,也足我们和大牛的区别正是在此吧

文章如果存在问题或者有更好的题解,希望大佬斧正和评论,希望大家和我一起进步一起优秀
posted @ 2021-02-25 22:34  21岁还不是架构师  阅读(89)  评论(0编辑  收藏  举报