[LeetCode] Implement strStr()

来源:互联网 发布:js return false 无效 编辑:程序博客网 时间:2024/05/16 19:53

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

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;    }};


0 0
原创粉丝点击