Implement strStr() LeetCode

APPROACH 

TIME: O(N) [indexOf will check whole string(haystack) for getting indexof string needle. Along with that contains function will check whether the string needle is present in the string haystack or not. So it may also traverse the whole string also.]

SPACE: O(1)[directly return index]


WAY 1 :


if(haystack.length()==0 && needle.length()==0){

            return 0;

        }

        else if(haystack.length()==0 && needle.length()!=0){

            return -1;

        }

        else{

            if(!haystack.contains(needle)){

                return -1;

            }

            else{

                return haystack.indexOf(needle);

            }

        }


LeetCode Time: 649 ms faster than 23.3%

LeetCode Space: 38.8MB less than 56.96%


======================================================================


WAY 2:


if(needle.length()==0){

            return 0;

        }

        else{

            if(haystack.length()==0){

                return -1;

            }

            else if(haystack.contains(needle)){

                return haystack.indexOf(needle);

            }

            else{

                return -1;

            }

        }


LeetCode Time: 669 ms faster than 21.81%

LeetCode Space: 38.6MB less than 66.33%


=========================================================================


WAY 3:

if(needle.length()==0){

            return 0;

        }

        else{

            if(haystack.contains(needle)){

                return haystack.indexOf(needle);

            }

           

            else{

                return -1;

            }

        }


LeetCode Time: 649 ms faster than 23.03%

LeetCode Space: 39MB less than 50.19%



Thanks for Reading.

"Knowledge grows by sharing not by saving.😇".

Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks