zoukankan      html  css  js  c++  java
  • C# 写 LeetCode easy #28 Implement strStr()

    28、Implement strStr()

    Implement strStr().

    Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

    Example 1:

    Input: haystack = "hello", needle = "ll"
    Output: 2
    

    Example 2:

    Input: haystack = "aaaaa", needle = "bba"
    Output: -1
    

    Clarification:

    What should we return when needle is an empty string? This is a great question to ask during an interview.

    For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

    代码

    static void Main(string[] args)
            {
                var haystack = "hello";
                var needle = "ll";
    
                var res = ImplementstrStr(haystack, needle);
                Console.WriteLine(res);
                Console.ReadKey();
            }
    
            private static int ImplementstrStr(string haystack, string needle)
            {
                var match = true;
                for (var i = 0; i <= haystack.Length - needle.Length; i++)
                {
                    match = true;
                    for (var j = 0; j < needle.Length; j++)
                    {
                        if (haystack[i + j] != needle[j])
                        {
                            match = false;
                            break;
                        }
                    }
                    if (match) return i;
                }
                return -1;

    解析

    输入:字符串

    输出:匹配位置

    思想:定义一个匹配变量match,从首字母循环,使用内循环逐一判断是否每个字母都能匹配,若不匹配立刻退出内循环。

    时间复杂度:O(m*n)  m和n分别是两个字符串长度。

  • 相关阅读:
    CSP_2019
    luogu_P1026 统计单词个数
    [SCOI2007]降雨量
    [HEOI2016/TJOI2016]排序
    LuoguP2698 【[USACO12MAR]花盆Flowerpot】
    LuoguP3069 【[USACO13JAN]牛的阵容Cow Lineup
    CF723D 【Lakes in Berland】
    CF799B T-shirt buying
    迪杰斯特拉算法(Dijkstra) (基础dij+堆优化) BY:优少
    Tarjan求有向图强连通分量 BY:优少
  • 原文地址:https://www.cnblogs.com/s-c-x/p/10144528.html
Copyright © 2011-2022 走看看