Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
暴力法
复杂度
时间 O(N^2) 空间 O(N)因为用了一个临时string存
思路
本题有很多高级算法可以在O(N)时间内解决问题,然而这已经超出面试的范畴。本题在面试中出现的作用就是考察基本的编程素养,以及边界条件的考虑。我们用暴力法即可。
1 public class Solution { 2 public int strStr(String haystack, String needle) { 3 if (haystack==null || needle==null) return -1; 4 for (int i=0; i<=haystack.length()-needle.length(); i++) { 5 String temp = haystack.substring(i, i+needle.length()); 6 if (temp.equals(needle)) { 7 return i; 8 } 9 } 10 return -1; 11 } 12 }
若要用O(1)的space,就一个一个比:
1 public class Solution { 2 public int strStr(String haystack, String needle) { 3 for (int i = 0; i<=haystack.length()-needle.length(); i++) { 4 for (int j = 0; ; j++) { 5 if (j == needle.length()) return i; 6 if (needle.charAt(j) != haystack.charAt(i + j)) break; 7 } 8 } 9 return -1; 10 } 11 }
推荐:
1 public class Solution { 2 public int strStr(String haystack, String needle) { 3 int start = 0; 4 // 如果剩下的字母不够needle长度就停止遍历 5 while(start <= haystack.length() - needle.length()){ 6 int i1 = start, i2 = 0; 7 while(i2 < needle.length() && haystack.charAt(i1)==needle.charAt(i2)){ 8 i1++; 9 i2++; 10 } 11 if(i2 == needle.length()) return start; 12 start++; 13 } 14 return -1; 15 } 16 }
KMP 参https://segmentfault.com/a/1190000003707284