Share my java solution


  • 0
    R

    The basic idea is find any substring that matchs the head of the needle, and then try to match the entire string. if the total length of current index+the length of needle is greater than the haystack, it means we can not find match.

    public int strStr(String haystack, String needle) {
    			if(haystack.length()==0&&needle.length()==0){
    				return 0;
    			}else if(needle.length()>haystack.length()){
    				return -1;
    			}else if(needle.length()==0){
    			    return 0;
    			}
    	        int i = 0;
    	        while(i<haystack.length()){
    	        	//find possible substring
    	        	if(haystack.charAt(i)==needle.charAt(0)){
    	        		if(i+needle.length()>haystack.length()){
    	        			return -1;
    	        		}
    	        		else if(haystack.substring(i, i+needle.length()).equals(needle))
    	        		{
    	        			return i;
    	        		}
    	        	}
    	        	i++;
    	        }
    	        return -1;
    	    }

  • 0
    H
    public int strStr(String haystack, String needle) {
        int lastPos = haystack.length() - needle.length();
        for(int i = 0; i <= lastPos; i++) {
            if(haystack.substring(i, i + needle.length()).equals(needle)) {
                return i;
            }
        }
        return -1;
    }
    

    My code. Actually no need to considering all special cases cause it won't go into the loop.


  • 0
    M

    it is correct but the run time could be as bad a O(nm).


Log in to reply
 

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