自己写测试用例,区别:字符串为 空串“ ”,空对象null 。
3.2 Implement strStr()
描述
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
分析
暴力算法的复杂度是O(m n),代码如下。更高效的的算法有KMP 算法、Boyer-Mooer 算法和
Rabin-Karp 算法。面试中暴力算法足够了,一定要写得没有BUG。
暴力匹配
// LintCode, Implement strStr()
// 暴力解法,时间复杂度O(N*M),空间复杂度O(1)
</pre><p><pre name="code" class="java">package leetCode;
public class strstr {
public static int strStrMy(String source, String target) {
if (source == null || target == null) {
return -1;
} else if (target.equals("")) {
return 0;
}
int i = 0, j = 0;
while(i < source.length()) {
if (j < target.length() && source.charAt(i) == target.charAt(j)) {
i++;
j++;
} else if (j == target.length()) {
break;
} else {
i = i - (j - 1);
j = 0;
}
}
if (j == target.length()) {
return i - target.length();
} else {
return -1;
}
}
public static int strStr(String haystack, String needle) {
if (needle.length() == 0)
return 0;
for (int i = 0;; i++) {
for (int j = 0;; j++) {
if (j == needle.length())
return i;
else if (i + j >= haystack.length())
return -1;
else if (needle.charAt(j) != haystack.charAt(i + j))
break;
}
}
}
public static void main(String[] args) {
String source = "";
String target = "a";
System.out.println("输出结果:" + strStr(source, target));
System.out.println("输出结果--strStrMy" + strStrMy(source, target));
System.out.println("输出结果空串.equals(null) :" + "".equals(null));
}
}