栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

实现 strStr()(力扣刷题day18)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

实现 strStr()(力扣刷题day18)

题目

实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。

题解
class Solution {
public:
    int strStr(string haystack, string needle) {
int i = 0;
	const char *ps1 = haystack.c_str();
	const char*ps2 = needle.c_str();
	const char *ps11 = haystack.c_str();
	const char*ps21 = needle.c_str();
	int len1 = haystack.size();
	int len2 = needle.size();
      if(haystack==""&&needle=="")
    return 0;
    if(len1==len2)
    {
        if(haystack == needle)
        return 0;
    }
	//如果needle的长度大于haystack,haystack不可能存在子串needle,直接返回NULL
  
	if (len2>len1)
		return -1;
	while (*ps1 != '')
	{
		while ((*ps1 == *ps2) && (*ps2 != ''))
		{
			ps1++;
			ps2++;
		}
		if (*ps2 == '')
		{
			return i;
		}
		else
		{
			ps2 = ps21;
			ps11++;
			ps1 = ps11;
			len1--;
            i++;
		}
		//此时haystack中剩余的字符串已经小于needle的长度,不必再继续查找
		if (len1
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/282321.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号