zoukankan      html  css  js  c++  java
  • LeetCode——实现 strStr()

    Q:Implement strStr().
    Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

    A:KMP算法
    kmp算法的思想就是:在匹配过程中,若发生不匹配的情况,如果next[j]>=0,则目标串的指针i不变,将模式串的指针j移动到next[j]的位置继续进行匹配;若next[j]=-1,则将i右移1位,并将j置0,继续进行比较。

        public static int strStr(String haystack, String needle) {
            if (needle == null || needle.length() == 0)
                return 0;
            int[] next = getNext(needle);
            int nIndex = 0;
            int hIndex = 0;
            while (nIndex != needle.length() && hIndex != haystack.length()) {
                //相等两个都往后放1
                if (haystack.charAt(hIndex) == needle.charAt(nIndex)) {
                    hIndex++;
                    nIndex++;
                } else if (next[nIndex] == -1) {
                    //第一个都没有相等的时候
                    hIndex++;
                } else {
                    //找到当前位置next数组中的index
                    nIndex = next[nIndex];
                }
            }
            if (nIndex == needle.length())
                return hIndex - nIndex;
            else
                return -1;
        }
    
        public static int[] getNext(String needle) {
            if (needle.length() == 1)
                return new int[]{-1};
            int[] next = new int[needle.length()];
            //next数组从-1开始
            next[0] = -1;
            next[1] = 0;
            for (int i = 2; i < needle.length(); i++) {
                for (int count = 1; count < i - 1; count++) {
                    String s1 = needle.substring(0, count + 1);
                    String s2 = needle.substring(i - count, i);
                    if (!s1.equals(s2)) {
                        next[i] = count;
                        continue;
                    }
                }
            }
            return next;
        }
    
  • 相关阅读:
    Linux 发展历史
    购物车0612版登陆与购物功能
    Linux 基本命令
    MySQL练习
    购物车登陆购物版
    MySQL阅读目录
    输入打印之佛祖辟邪
    mysql存储引擎
    函数对象、函数嵌套、名称空间与作用域、装饰器
    【计算机网络】哈尔滨工业大学MOOC-计算机网络 第2周 计算机网络概述(下) 作业2
  • 原文地址:https://www.cnblogs.com/xym4869/p/12552998.html
Copyright © 2011-2022 走看看