Skip to content
Snippets Groups Projects

Implement strStr()

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Kiryuu Sakuya
    Program.cs 1.39 KiB
    using System;
    using System.Collections.Generic;
    
    namespace test
    {
        class Program
        {
            public static int StrStr(string haystack, string needle)
            {
                bool match = false;
                int i = 0;
                if (haystack == "" && needle == "")
                    return 0;
                if (haystack != "" && needle == "")
                    return 0;
                if (haystack.Length < needle.Length)
                    return -1;
                for (i = 0; i < haystack.Length; i++)
                {
                    if (match == false)
                    {
                        if (haystack[i] != needle[0])
                            continue;
                        if (i + needle.Length > haystack.Length)
                            break;
                        int j = 0;
                        while (haystack[i + j] == needle[j])
                        {
                            j++;
                            if (j != needle.Length) continue;
                            match = true;
                            break;
                        }
                    }
                    else
                        break;
                }
    
                if (match == true)
                {
                    return i - 1;
                }
                return -1;
            }
            public static void Main(string[] args)
            {
                string a = "mississippi";
                string b = "issipi";
                Console.WriteLine(StrStr(a, b));
            }
    
        }
    }
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment