1 package leetcode; 2 3 public class demo_28 { 4 public int strStr(String haystack, String needle) { 5 int i; 6 if(needle=="") {return 0;} 7 if(haystack.contains(needle)) { 8 for(i=0;i<haystack.length();i++) { 9 if(haystack.substring(i,i+needle.length()).equals(needle)) { 10 break; 11 } 12 } 13 return i; 14 } 15 else { 16 return -1; 17 } 18 } 19 public static void main(String[] args) { 20 // TODO Auto-generated method stub 21 demo_28 d28 = new demo_28(); 22 String haystack="hello"; 23 String needle="ll"; 24 System.out.println(d28.strStr(haystack, needle)); 25 } 26 27 }
简化版
1 return haystack.indexOf(needle);
KMP算法