Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
暴力法,从haystack第一个字符开始查找needle。
代码如下:
1 public class Solution { 2 public String strStr(String haystack, String needle) { 3 if(haystack == null) 4 return null; 5 6 if(needle.length() == 0) 7 return haystack; 8 9 int i,j = 0; 10 for(i = 0;i < haystack.length() - needle.length() + 1;i++){ 11 for(j = 0;j < needle.length();j++){ 12 if(haystack.charAt(i+j) != needle.charAt(j)) 13 break; 14 } 15 if(j == needle.length()) 16 return haystack.substring(i,haystack.length()); 17 } 18 return null; 19 } 20 }