Implement strStr().java
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.spa
Update (2014-11-02):
code
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 the reload button to reset your code definition.it
public class Solution { public int strStr(String haystack, String needle) { int L1=haystack.length(); int L2=needle.length(); char[] n=needle.toCharArray(); if(needle.equals(null)||haystack.equals(null)||haystack==null||needle==null||L2>L1)return -1; for(int i=0;i<=L1-L2;i++){ int j; for( j=0;j<L2;j++){ if(haystack.charAt(i+j)!=n[j])break; } if(j==L2) return i; } return -1; } }