zoukankan      html  css  js  c++  java
  • Leetcode Implement strStr()

    Implement strStr().

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


    解题思路:

    解题想法是,从haystack的第一个位置,开始逐个判断是不是子串。如果整个子串都匹配了,那么就返回,否则继续往下挪位置。

    Complexity: O(mn) , m is the length of haystack, n is the length of needle

    还有一个KMP解法,算法复杂度很好,但目前没研究。以后再说。


    Java code:

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

    Reference:

    1. http://www.programcreek.com/2012/12/leetcode-implement-strstr-java/

    2. http://jakeboxer.com/blog/2009/12/13/the-knuth-morris-pratt-algorithm-in-my-own-words/

    3. http://www.cnblogs.com/springfor/p/3896469.html

  • 相关阅读:
    Cookie
    JS开发常用工具函数
    手动搭建Vue之前奏:搭建webpack项目
    Redis的下载与安装
    Redis官方Tutorial
    Redis之datatype概述
    18 SQL优化
    16 SQL Mode
    17 MySQL的小技巧
    14 事务控制和锁定语句
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4866205.html
Copyright © 2011-2022 走看看