2八、Implement strStr()this
Implement strStr().spa
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.code
Example 1:blog
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:字符串
Input: haystack = "aaaaa", needle = "bba" Output: -1
Clarification:string
What should we return when needle
is an empty string? This is a great question to ask during an interview.it
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().io
代碼:class
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分別是兩個字符串長度。