LeetCode 28 — Implement strStr()(C++ Java Python)

题目: http://oj.leetcode.com/problems/implement-strstr/

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
         感谢阅读,欢迎评论!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值