当前位置:网站首页>[LeetCode]28. Implement strstr()

[LeetCode]28. Implement strstr()

2022-06-13 00:12:00 PowerDon

Realization  strStr()  function .

Given a  haystack String and a needle character string , stay haystack Find in string needle The first place the string appears ( from 0 Start ). If it doesn't exist , Then return to   -1.

Example 1:

Input : haystack = “hello”, needle = “ll”
Output : 2
Example 2:

Input : haystack = “aaaaa”, needle = “bba”
Output : -1
explain :

When  needle  When it's an empty string , What value should we return ? This is a good question in an interview .

For this question , When  needle  When it's an empty string, we should return 0 . This is related to C Linguistic  strstr()  as well as Java Of  indexOf()  The definition matches .

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/implement-strstr
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

public class Solution {
    
    public int StrStr(string haystack, string needle) {
    
        //  Super lazy writing 
        // return haystack.IndexOf(needle);

        //  Fancy writing 
        // if(needle.Length == 0){
    
        // return 0;
        // }
        // string[] temp = haystack.Split(needle);
        // if(temp.Length > 1){
    
        // return temp[0].Length;
        // }
        // return -1;

        //  There is no technical content 
        if(needle.Length == 0){
    
            return 0;
        };

        for(int i = 0; i < haystack.Length; i++){
    
            if(haystack.Length - i < needle.Length){
    
                return -1;
            }

            int count = 0;
            for(int j = 0; j < needle.Length; j++){
    
                if(haystack[i+j] != needle[j]){
    
                    break;
                }
                ++count;
                //Console.WriteLine($"{haystack[i+j]}:{needle[j]}:Count:{i-count}");
                if(count == needle.Length){
    
                    return (i+j+1)-count;
                }
            }
        }
        return -1;

        //  Water in the head 
        // if(needle.Length == 0){
    
        // return 0;
        // }
        // int hayCount = 0;
        // int neeCount = 0;
        // int count = 0;
        // int target = 0;
        // while(hayCount < haystack.Length){
    
        // Console.WriteLine(hayCount+":"+neeCount);
        // if(haystack[hayCount] == needle[neeCount]){
    
        // hayCount++;
        // neeCount++;
        // count++;
        // }else{
    
        // hayCount++;
        // count = 0;
        // neeCount = 0;
        // target++;
        // hayCount = target;
        // }

        // if(count == needle.Length){
    
        // return hayCount-count;
        // }
        // }
        // return -1;
    }
}
原网站

版权声明
本文为[PowerDon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280602300737.html