标签:
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Below is my first direct solution, which looks complex in different case checking using if, else.
1 public int strStr(String haystack, String needle) { 2 if (haystack == null || needle == null) 3 return -1; 4 5 int len1 = haystack.length(); 6 int len2 = needle.length(); 7 8 if (len2==0) 9 return 0; 10 11 if (len1 <= len2){ 12 if (haystack.equals(needle)) return 0; 13 else return -1; 14 } 15 16 for (int i = 0; i < len1; i ++){ 17 if (haystack.charAt(i) == needle.charAt(0)){ 18 if (i+len2 > len1) 19 return -1; 20 String temp = haystack.substring(i, i+len2); 21 if (needle.equals(temp)) 22 return i; 23 } 24 } 25 return -1; 26 }
标签:
原文地址:http://www.cnblogs.com/timoBlog/p/4674957.html