C# solution: two pointers


  • 0
    B
    public class Solution 
    {
        public int StrStr(string haystack, string needle) 
        {
            if (needle.Length == 0) return 0;
            if (needle.Length > haystack.Length) return -1;
    
            var needleIndex = 0;
    
            for(int i = 0; i < haystack.Length; i++)
            {
                if (haystack[i] == needle[needleIndex])
                {
                    needleIndex++;
    
                    if (needleIndex == needle.Length) return i - needleIndex + 1;
                }
                else
                {
                    i -= needleIndex;
                    needleIndex = 0;
                }
            }
    
            return -1;
        }
    }
    

Log in to reply
 

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