题目:
http://oj.leetcode.com/problems/implement-strstr/
采用暴力方法,注意下标不要越界。(KMP待补充)
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
题目翻译:
实现strStr()。
返回指向needle在haystack中第一次出现位置的指针,如果needle不是haystack的一部分,则返回null。
采用暴力方法,注意下标不要越界。(KMP待补充)
C++实现1:
class Solution {
public:
char *strStr(char *haystack, char *needle) {
if(*needle == NULL)
{
return haystack;
}
char *p1;
char *p2 = needle + 1;
char *p1_advance = haystack;
while(*p2)
{
++p1_advance;
++p2;
}
while(*p1_advance)
{
p1 = haystack;
p2 = needle;
while(*p2 && *p1 == *p2)
{
++p1;
++p2;
}
if(*p2 == NULL)
{
return haystack;
}
++haystack;
++p1_advance;
}
return NULL;
}
};
C++实现2:
class Solution {
public:
char *strStr(char *haystack, char *needle) {
std::string str(haystack);
std::string target(needle);
if(target.empty())
{
return haystack;
}
int len1 = str.length();
int len2 = target.length();
if(len1 < len2)
{
return NULL;
}
for(int i = 0; i <= len1 - len2; ++i)
{
int j = 0;
int k = i;
while(j < len2 && target[j] == str[k])
{
k++;
j++;
}
if(j == len2)
{
return (char*)str.substr(i).c_str();
}
}
return NULL;
}
};
Java实现:
public class Solution {
public String strStr(String haystack, String needle) {
if (needle != null && needle.isEmpty()) {
return haystack;
}
int len1 = haystack.length();
int len2 = needle.length();
if (len1 < len2) {
return null;
}
for (int i = 0; i <= len1 - len2; ++i) {
int j = 0;
int k = i;
while (j < len2 && needle.charAt(j) == haystack.charAt(k)) {
j++;
k++;
}
if (j == len2) {
return haystack.substring(i);
}
}
return null;
}
}
Python实现:
class Solution:
# @param haystack, a string
# @param needle, a string
# @return a string or None
def strStr(self, haystack, needle):
if not needle:
return haystack
len1 = len(haystack)
len2 = len(needle)
if len1 < len2:
return None
for i in range(len1 - len2 + 1):
j = 0
k = i
while j < len2 and needle[j] == haystack[k]:
j += 1
k += 1
if j == len2:
return haystack[i:]
return None
感谢阅读,欢迎评论!