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.

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


你可能感兴趣的:(leetcode--Implement strStr())