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分别是两个字符串长度。

  • 相关阅读:
    P3704 [SDOI2017]数字表格
    CF 700 E. Cool Slogans
    杜教筛学习笔记
    [BOI2004]Sequence 数字序列(左偏树)
    [WC2007]剪刀石头布(最大流)
    [NOI2009]变换序列(二分图匹配)
    文理分科(最小割)
    上帝与集合的正确用法(欧拉定理)
    [HAOI2008]圆上的整点(数论)
    主席树学习笔记
  • 原文地址:https://www.cnblogs.com/s-c-x/p/10144528.html
Copyright © 2011-2022 走看看