leetcode 28 c++ 实现strstr

简介: 暴力破解从前往后找,结果超时了。。。。。。。。。。。。int strStr(string haystack, string needle) { if (needle.

暴力破解

从前往后找,结果超时了。。。。。。。。。。。。

int strStr(string haystack, string needle) {
	if (needle.length() == 0) return 0;
	if (needle.length() > haystack.length()) return -1;

	int n_index = 0;
	for (int i = 0; i < haystack.length(); i++) {
		if (n_index == needle.length()) {
			return i - needle.length();
		}
		if (haystack[i] == needle[n_index]) {
			n_index++;
		}
		else {
			if (n_index > 0) {
				n_index = 0;
				n_index = 0;
				//从上一段重合的第二个字符开始找,不然第一段和第二段重合的会让你丢失第一段中后面的元素
				i = i - needle.length() + 1;
			}
		}
	}
	if (n_index < needle.length()) return -1;
	else if (n_index == needle.length()) return haystack.length() - needle.length();
}

 

目测输在了每次我比较失败之后都会让 i 回到开始相同的点的后一个位置。来一个复杂度为O(n)的解法。

1、每次比较之前,判断余下的串的长度是否超过子串余下的串的长度

2、两个同步比较,使用continue跳出循环,降低时间复杂度

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.size()==0)
            return 0;
        for(int i=0;i<haystack.size();i++){
            if(i+needle.size()-1>=haystack.size())
                return -1;
            int flag=1;
            for(int j=0;j<needle.size();j++){
                if (haystack[i+j]==needle[j])
                    continue;
                flag=0;
            }
            if (flag==1)
                return i;
        }
        return -1;
    }
};

 

相关文章
|
13天前
【LeetCode 21】28. 实现 strStr()
【LeetCode 21】28. 实现 strStr()
28 0
|
5月前
|
算法 C语言 容器
从C语言到C++_18(stack和queue的常用函数+相关练习)力扣(上)
从C语言到C++_18(stack和queue的常用函数+相关练习)力扣
43 0
|
4月前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
4月前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-1
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
5月前
|
算法 C语言 容器
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145(下)
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145
59 7
|
5月前
|
存储 算法 C语言
从C语言到C++_39(C++笔试面试题)next_permutation刷力扣
从C语言到C++_39(C++笔试面试题)next_permutation刷力扣
54 5
|
5月前
|
存储 C语言 容器
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别(下)
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别
41 1
|
5月前
|
存储 C语言 容器
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别(中)
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别
45 1
|
5月前
|
存储 自然语言处理 C语言
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别(上)
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别
58 1
|
5月前
|
C语言
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145(中)
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145
51 1