28. Implement strStr()

问题

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

思路

  1. public class Solution {
  2. public int strStr(String haystack, String needle) {
  3. if(needle.length() == 0) return 0;
  4. int h ,t;
  5. for(h = 0;h <= haystack.length() - needle.length();h++)
  6. {
  7. for(t = 0;t < needle.length();t++)
  8. if(haystack.charAt(h+t) != needle.charAt(t)) break;
  9. if(t == needle.length())
  10. return h;
  11. }
  12. return -1;
  13. }
  14. }