• 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

  • 相关阅读:
    asp.net 页面定时跳转的小技巧
    获得 Windows phone 设备的信息
    如何自定义ToggleSwitch控件样式(转)
    云推送注意(MSDN链接)
    回顾:线程和进程的区别
    WebGL
    13种提升基于MVVM模式的WP7程序性能的方法(转)
    sample_code
    网址收藏
    Net中de日期格式
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4866205.html
Copyright © 2020-2023  润新知