Implement strStr() 实现strStr函数 @ LeetCode

来源:互联网 发布:什么是大数据交易平台 编辑:程序博客网 时间:2024/05/28 03:01

题目:

实现strStr() 函数


经典题目!练习必做到bug free题

思路:

1.用indexOf找到第一次出现的index,如果找到则调用substring,否则返回null ==> 因为用到了indexOf,所以面试时候肯定不可以

2.用O(n2)的暴力匹配(推荐)

3 KMP O(n), 面试时一般不会要求写出

/** * Implement strStr(). *  * Returns a pointer to the first occurrence of needle in haystack, or null if * needle is not part of haystack. *  */public class S28 {public static void main(String[] args) {String haystack = "testing test";String needle = "test";System.out.println(strStr(haystack, needle));}public static String strStr(String haystack, String needle) {// 找到出现第一次的index        int idx = haystack.indexOf(needle);        if(idx < 0){// 没找到        return null;        }else{// 利用index得到substring        return haystack.substring(idx);        }    }}



值得注意的几点:

1 输入检测

2 越界检测

public class Solution {    public String strStr(String haystack, String needle) {        if(haystack==null || needle==null || needle.length()>haystack.length()){            return null;        }        int i=0, j=0;        for(i=0; i<=haystack.length()-needle.length(); i++){    // Notice <= here!            for(j=0; j<needle.length(); j++){                if(haystack.charAt(i+j) != needle.charAt(j)){                    break;                }            }            if(j == needle.length()){                return haystack.substring(i);            }        }        return null;    }}




原创粉丝点击