leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

find-index-of-first-occurence.dart (1347B)


      1 //Find the first occurence of a substring in a given string
      2 //if the substring is not found return -1. I completed this using
      3 //the sliding window method of checking if any given character is the word
      4 //and then moving to the next charcter if it is not. This is an O(M * N) time
      5 //complexity function.
      6 //Runtime: 206ms Beats: 99.45%
      7 //Memory: 139.3MB Beats: 87.91%
      8 
      9 
     10 
     11 
     12 void main(){
     13     Solution sol = new Solution();
     14     print(sol.strStr("Test input raoiset", "input"));
     15 }
     16 
     17 class Solution {
     18   int strStr(String haystack, String needle) {
     19     
     20     if(haystack == needle){
     21         return 0;
     22     }
     23     if(needle.length == 1){
     24         for(int i = 0; i < haystack.length ; ++i){
     25             if(haystack[i] == needle){
     26                 return i;
     27             }
     28         }
     29         return -1;
     30     }
     31     int x = 0;
     32     for(int i = 0; i < haystack.length; ++i){
     33         if(haystack[i] == needle[0]){
     34             int count = 1;
     35             for(x = i + 1; x < haystack.length ; ++x){
     36                 if(count == needle.length){
     37                     return x - needle.length;
     38                 }
     39                 if(haystack[x] != needle[count]){
     40                     break;
     41                 }
     42                 count += 1;
     43             }
     44             if(count == needle.length){
     45                 return x - needle.length;
     46             }
     47         }
     48     }
     49     return -1;
     50   }
     51 }