前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >28. 实现strStr()

28. 实现strStr()

作者头像
祝你万事顺利
发布2019-06-25 10:17:54
5810
发布2019-06-25 10:17:54
举报
文章被收录于专栏:Unity游戏开发Unity游戏开发

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。

示例 1:

输入: haystack = "hello", needle = "ll" 输出: 2

示例 2:

输入: haystack = "aaaaa", needle = "bba" 输出: -1

说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

代码语言:javascript
复制
public class Solution {
    public int StrStr(string haystack, string needle) {
       int fstrIndex = 0;
            int index = 0;
            if (needle == "")
            {
                return 0;
            }
            if (haystack.Length < needle.Length)
            {
                return -1;
            }
            if (haystack.Length == needle.Length)
            {
                if (haystack != needle)
                {
                    return -1;
                }
            }
            for (int i = 0; i < haystack.Length; i++)
            {
                if (haystack[i] == needle[fstrIndex])
                {
                    index = i;
                    for (int j = 0; j <needle.Length && index<haystack.Length; j++)
                    {
                        if (haystack[index] != needle[j])
                        {
                            break;
                        }
                        else if (haystack[index]==needle[j] && j == needle.Length -1)
                        {
                            return i;
                        }
                        index++;
                    }
                }
            }
            return -1;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.06.25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档