Java 2ms solution, beats 70%, easy to understand


  • 0
    R
    public int strStr2(String haystack, String needle) {
    		if (haystack.length() == 0 && needle.length() == 0)
    			return 0;
    		if (needle.length() == 0)
    			return 0;
    		// if the remaining elements are less than the length of needle, end the loop
    		for (int i = 0; i <= haystack.length() - needle.length(); i++) {
    			if (haystack.charAt(i) == needle.charAt(0)) {
    				String sub = haystack.substring(i, i+needle.length());
    				if (sub.equals(needle))
    					return i;
    				else
    					continue;
    			}
    		}
    		return -1;
    	}

Log in to reply
 

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