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

 

相关文章
|
1月前
|
Go C++
【力扣】2696. 删除子串后的字符串最小长度(模拟 栈 C++ Go实现栈)
【2月更文挑战第18天】2696. 删除子串后的字符串最小长度(模拟 栈 C++ Go实现栈)
34 6
|
1月前
|
C++
两种解法解决 LeetCode 27. 移除元素【C++】
两种解法解决 LeetCode 27. 移除元素【C++】
|
8天前
|
算法 Java C语言
C++和Java中的随机函数你玩明白了吗?内附LeetCode470.rand7()爆改rand10()巨详细题解,带你打败LeetCode%99选手
C++和Java中的随机函数你玩明白了吗?内附LeetCode470.rand7()爆改rand10()巨详细题解,带你打败LeetCode%99选手
|
4月前
|
算法 C++
【LeetCode】【C++】string OJ必刷题
【LeetCode】【C++】string OJ必刷题
30 0
|
6月前
|
存储 搜索推荐 算法
【C/C++ 力扣leetcode】4道简单题
【C/C++ 力扣leetcode】4道简单题
存储 编译器 Linux
15 0
|
1月前
|
Go C++
【力扣】2645. 构造有效字符串的最小插入数(动态规划 贪心 滚动数组优化 C++ Go)
【2月更文挑战第17天】2645. 构造有效字符串的最小插入数(动态规划 贪心 滚动数组优化 C++ Go)
30 8
|
6月前
|
存储 C语言 C++
【C/C++刷题——leetcode】查找字符串中最大的子串
【C/C++刷题——leetcode】查找字符串中最大的子串
133 0
|
3月前
|
算法 C++ 机器人
力扣 C++|一题多解之动态规划专题(1)
力扣 C++|一题多解之动态规划专题(1)
41 0
力扣 C++|一题多解之动态规划专题(1)
|
3月前
|
C++ 存储 Serverless
力扣C++|一题多解之数学题专场(2)
力扣C++|一题多解之数学题专场(2)
27 0
力扣C++|一题多解之数学题专场(2)