zoukankan      html  css  js  c++  java
  • Java for LeetCode 028 Implement strStr()

    Implement strStr().

    Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

    解题思路一:

    暴力枚举,JAVA实现如下:

            static public int strStr(String haystack, String needle) {
            for(int i=0;i<=haystack.length()-needle.length();i++)
            	if(haystack.substring(i, i+needle.length()).equals(needle))
            		return i;
            return -1;
        }
    

     解题思路二:

    经典的KMP算法

    参考链接:

    http://kb.cnblogs.com/page/176818/

    http://blog.csdn.net/zxasqwedc/article/details/41956381

    JAVA 实现

    	static public int strStr(String haystack, String needle) {
    		int[] next = new int[needle.length()+1];
    		int i = 0, j = -1;
    		//i可以代表索引,其实也可以理解为一个间隔,j代表前面已匹配的
    		//next[1,next.length-1] 恰好表示部分匹配值
    		next[0] = -1;
    		while (i < needle.length()) {
    			if (j == -1 || needle.charAt(i) == needle.charAt(j)) {
    				i++;
    				j++;
    				next[i] = j;
    			} 
    			else
    				j = next[j];
    		}	
    		i = 0;
    		j = 0;
    		while (i < haystack.length()) {
    			if (j == -1 || haystack.charAt(i) == needle.charAt(j)) {
    				i++;
    				j++;
    			} else
    				j = next[j];//是next[j]不是next[j-1],算法核心
    			if (j == needle.length())
    				return i - needle.length();
    		}
    		return -1;
    	}
    
  • 相关阅读:
    记录一下周末作业
    超链接的 使用和按钮添加
    学习了网页设置上传视频
    Java-JDK安装及环境变量配置
    java-库存管理案例
    java-DateFormat
    java-正则表达式练习
    java-StringBuffer类
    java面对对象-匿名对象
    java static和final关键字
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4474658.html
Copyright © 2011-2022 走看看