Title Description:
Implement strStr ().
Returns the index of the first occurrence of needle in haystack, or-1 if needle are not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String , please click on the reload button to reset your code Definition.
Problem Solving Ideas:
From the beginning, match one by one.
Pay attention to special circumstances.
The code is as follows:
public class Solution {public static int strStr (String haystack, string needle) {int haystacklength = Haystack.length (); int needlelength = Needle.length (); int j = 1;if (Needlelength = = 0) return 0;if (Needlelength > Haystacklength) return -1;for (int i = 0; I <= haystacklength-needlelength; i++) {if (Haystack.charat (i) = = Needle.charat (0)) {for (j = 1; J < Needlelength; J + +) {if (Haystack.charat (i + j)! = Needle.charat (j)) break; if (j = = needlelength) return i;}} return-1;}}
Java [Leetcode 28]implement strStr ()