【LeetCode】C# 28、Implement strStr()

来源:互联网 发布:java 未来前景 编辑:程序博客网 时间:2024/06/07 01:41

Implement strStr().

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

find needle in haystack 大海捞针。在长串中找短串。
思路是遍历长串,如果首字符等于短串首字符,就进入循环遍历短串看是否与长串该指针开始的短串相同。

public class Solution {    public int StrStr(string haystack, string needle) {        if (needle == "") return 0;        for(int i=0;i<haystack.Length;i++){            int j = 0;            while((i+j)<haystack.Length && haystack[i+j]==needle[j]){                if(j==needle.Length-1) return i;                j++;            }            if(i+j==haystack.Length) return -1;        }        return -1;    }}
原创粉丝点击