C# solution for share two pointer


  • 1
    Y

    public class Solution {

    public int StrStr(string haystack, string needle) {
    
        
        var hayStackLength = haystack.Length;
    
        var needleLength = needle.Length;
    
        if(haystack == needle)
        {
            return 0;
        }
        
        if(needleLength == 0)
        {
            return 0;
        }
        
        if(hayStackLength == 0)
        {
            return -1;
        }
        
        for(int i = 0; i < hayStackLength; i++)
        {
            if(needleLength > hayStackLength - i)
            {
                return -1;
            }
            
            if(haystack[i] == needle[0])
            {
                int j = 0;
                for(; j < needleLength; j++)
                {
                    if(needle[j] != haystack[i + j])
                    {
                        break;
                    }
                }
                
                if(j == needleLength && needle[j-1] == haystack[i + j-1])
                {
                    return i;
                }
            }
        }
        
        return -1;
        
    }
    

    }


  • 0
    L

    The condition needle[j-1] == haystack[i + j-1] is not required.


  • 0
    Y

    yes, you are right, but not quite understand, why don't we need such a condition, do we need to worry about the last one is unequal?


  • 0
    L

    j == length does already check the last character of needle


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.