LeetCode problem#28
Find the Index of the First Occurrence in a String
Solved in 1 languageC#
Solution
21 lines
1public class Solution {
2 public int StrStr(string haystack, string needle) {
3 for (int i = 0; i <= haystack.Length - needle.Length; i++)
4 {
5 bool matches = true;
6 for (int j = 0; j < needle.Length; j++)
7 {
8 if (haystack[i + j] != needle[j])
9 {
10 matches = false;
11 break;
12 }
13 }
14 if (matches)
15 {
16 return i;
17 }
18 }
19 return -1;
20 }
21}Want a walkthrough of this C# solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.