题目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
链接:https://leetcode.com/problems/implement-strstr/#/description
4/22/2017
注意的问题:
1. 特殊情况的判断,比如第4-7行
2. 第14行在内循环里,如果在内循环外那么有可能只是最后一个字母不匹配,跟Python for-else有不同吗?是一样的,看下面老大爷的解法
3. 第10行注意i的退出条件
1 public class Solution { 2 public int strStr(String haystack, String needle) { 3 // write your code here 4 if (haystack == null || needle == null) { 5 return -1; 6 } else if (needle.length() == 0) { 7 return 0; 8 } 9 int j; 10 for (int 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 } else if (j == needle.length() - 1) { 15 return i; 16 } 17 } 18 } 19 return -1; 20 } 21 }
翻看了下老大爷的笔记,老大爷返回i那里写得好,第15行
1 public int strStr(String source, String target) { 2 // write your code here 3 if (source == null || target == null) { 4 return -1; 5 } else if (target.length() == 0) { 6 return 0; 7 } 8 for (int i = 0; i < source.length() - target.length() + 1; i++) { 9 int j; 10 for (j = 0; j < target.length(); j++) { 11 if (source.charAt(i + j) != target.charAt(j)) { 12 break; 13 } 14 } 15 if (j == target.length()) return i; 16 } 17 return -1; 18 }
其他算法之后再补上
KMP
robin-karp