Implement strStr()

Implement strStr().

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

Update (2014-11-02):

The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.


public class Solution {
    public int strStr(String haystack, String needle) {
        int L1=haystack.length();
		int L2=needle.length();
		char[] n=needle.toCharArray();
		if(needle.equals(null)||haystack.equals(null)||haystack==null||needle==null||L2>L1)return -1;
		
		for(int i=0;i<=L1-L2;i++){
			int j;
			for( j=0;j<L2;j++){
				if(haystack.charAt(i+j)!=n[j])break;
			}
			if(j==L2)
				return i;
		}
		return -1;
    }
}


原文地址:https://www.cnblogs.com/gaoxiangde/p/4379841.html