LeetCode OJ 28 Implement strStr()
题目描述:
Implement strStr().
Returns the index of the first occurrenceof needle in haystack, or -1 if needle is not part of haystack.
题目理解:
给定两个字符串haystack和needle,返回字符串needle第一次出现字符串haystack中的位置,如果needle没有在haystack中出现,则返回-1。
测试用例:
功能测试:两个字符串相等; needle字符串长度小于haystack的长度;needle在haystack中出现多次/一次/零次;
特殊输入:needle为空;haystack为空;都为空;
题目分析:
1. 首先对特殊输入的情况做处理:needle为空、haystack为空、都为空、needle字符串长度大于haystack的长度;
2. strStr("","") strStr("aaaa","") 都返回0;
3. 维护两个指针
p_start:表示在haystack中进行匹配字符串操作的开始位置;
p_dist:表示已匹配的字符距离开始位置位置p_start的距离,该距离<needle.length(),该距离==needle.length()时,表示已经匹配完了needle中的所有字符;
4. 用二重循环实现匹配
我的解答:
public static int strStr(String haystack, String needle) {
if (needle.equals("")) {
return 0;
} else {
if (needle.length() == 0 || needle.length() > haystack.length()) return -1;
else {
for (int p_start = 0; p_start <= haystack.length(); p_start++) {
for (int p_dist = 0; p_dist <= needle.length(); p_dist++) {
if (p_dist == needle.length()) return p_start;
if (p_start + p_dist >= haystack.length()) return -1;
if (haystack.charAt(p_start + p_dist) != needle.charAt(p_dist)) break;
}
}
}
}
return -1;
}
简洁解答:
public int strStr(String haystack, String needle) {
for (int i = 0; ; i++) {
for (int j = 0; ; j++) {
if (j == needle.length()) return i;
if (i + j == haystack.length()) return -1;
if (needle.charAt(j) != haystack.charAt(i + j)) break;
}
}
}
上述代码对特殊输入:needle为空、haystack为空、都为空、needle字符串长度大于haystack的长度都能做有效处理,不需要在前面额外处理