[LeetCode] Implement strStr()

本文介绍了一个字符串匹配算法的具体实现,特别关注于处理各种边界条件,如空字符串和长字符串的特殊情况。通过C++代码示例展示了如何遍历目标字符串并查找模式出现的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这种题目主要是各种边界条件的处理。首先是没有考虑输入是“”和“”的情况,另外没有考虑长度很长的情况下的会超时。所以又加上了字符串长度的判断。

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
		if (haystack == NULL || needle == NULL) {
			return NULL;
		}

		char* tempHaystack = haystack;
		char* tempNeedle = needle;
		int lengthHaystack = 0;
		int lengthNeedle = 0;

		while (*tempHaystack++ != '\0') {
			++lengthHaystack;
		}

		while (*tempNeedle++ != '\0') {
			++lengthNeedle;
		}

		do {
			char* tempHaystack = haystack;
			char* tempNeedle = needle;

			while (*tempNeedle != '\0') {
				if (*tempNeedle == *tempHaystack){
					++tempNeedle;
					++tempHaystack;
				}
				else {
					break;
				}
			}

			if (*tempNeedle == '\0') {
				return haystack;
			}
			else {
				++haystack;
				--lengthHaystack;
			}
		} while (*haystack != '\0' && lengthHaystack >= lengthNeedle);

		return NULL;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值