Just 1ms time cost !Use a simple version of indexOf method from java String Class


  • 0
        // it's just a simple version of indexOf method 
        // from java String type
        public int strStr(String haystack, String needle) 
        {
            char[] source = haystack.toCharArray();
    		char[] target = needle.toCharArray();
    		int sourceCount = source.length;
     		int targetCount = target.length;
    		
    		if (sourceCount == 0)
    		{
    			return (targetCount == 0 ? sourceCount : -1);
    		}
    		if (targetCount == 0)
    		{
    		    return 0;
    		}
    
    		char first = target[0];
    		int max = sourceCount - targetCount;
    
    		for (int i = 0; i <= max; i++)
    		{
    			/* Look for first character. */
    			if (source[i] != first)
    			{
    				while ( ++i <= max && source[i] != first);
    			}
    
    			/* Found first character, now look at the rest of v2 */
    			if (i <= max)
    			{
    				int j = 0;
    				int k = i ;
    				int end =  k + targetCount;
    				while (k < end)
    				{
    				    if (source[k] != target[j])
    				    {
    				        break;
    				    }
            	        j++;
            	        k++;
                    }
                    // matched
    				if (k == end)
    				{
    					return i;
    				}
    				// if not matched, from next i to start
    			}
    		}
    		return -1;
        }

Log in to reply
 

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