Short and fast C# Accepted Solution


  • 0
    L
    public class Solution {
        public int StrStr(string haystack, string needle) {
            int i = 0;
            while (i < haystack.Length - needle.Length + 1)
            {
                int j;
                for (j = i; j < i + needle.Length; j++)
                    if (haystack[j] != needle[j - i])
                        break;
                if (j == i + needle.Length) return i;
                i++;
            }
            return -1;
        }
    }

  • 0
    H

    With 2 for loop

    public class Solution {
     public int StrStr(string haystack, string needle) {
        // Check the haystack and needle for null
            if (haystack.Length == needle.Length && haystack.Length == 0)
                return 0;
    
            // Check the haystack lenght
            if (needle.Length == 0)
                return 0;
    
            // Check the boundary and the length
            for (int i = 0; i < haystack.Length - needle.Length + 1; i++)
            {
                for (int j = 0; j < needle.Length; j++)
                {
                    if (!haystack[i + j].Equals(needle[j]))
                        break;
                    if (j == needle.Length - 1)
                        return i;
                }
            }
            return -1;
    }
    

    }


Log in to reply
 

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