C# solution


  • 0
    A

    May be it is not best solution, I think "if else" can be more complected.

     
    public class Solution {
        public int StrStr(string haystack, string needle) {
            int ind=	haystack.IndexOf(needle);
            int my_i=-1;
           if(needle.Length==0)
               return 0;
            else if(haystack.Length==needle.Length && haystack==needle)
            {
              return 0;   
            }
            for(int i=0;i<=haystack.Length-needle.Length;i++)
            {
                if(haystack[i]==needle[0])
                { 
                    for(int j=0;j<needle.Length;j++)
                    { 
                        //Console.WriteLine(haystack[i+j]);
                        if(haystack[i+j]==needle[j])
                        {
                           my_i=i; 
                        }
                        else
                        {
                            my_i=-1;
                            break;
                        }
                    }
                    if( my_i>-1)
                    { return  my_i;}
                }
            }
           return  my_i;
        }
    }
    ``

Log in to reply
 

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