My Java Solution


  • -1
    S

    public class Solution {
    public int strStr(String haystack, String needle) {
    if(needle.length() == 0){
    return 0;
    }

    	if(needle.length() > haystack.length()){
    		return -1;
    	}
    	
    	int index = haystack.indexOf(needle.charAt(0));
        int targetLength = needle.length();
        boolean match = false;
        while(index != -1 && index + targetLength <= haystack.length()){
        	if(haystack.substring(index, index + targetLength).equals(needle)){
        		match = true;
        		break;
        	}
        	
        	index = haystack.indexOf(needle.charAt(0), index + 1);
        }
        
        return match? index : -1;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.