jayati

Find the Index of the First Occurrence in a String

Feb 9th, 2023
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int strStr(string haystack, string needle) {
  4.         int i=0;
  5.        
  6.         int pos;
  7.         bool f=true;
  8.         if(haystack.length()<needle.length())
  9.         {
  10.             return -1;
  11.         }
  12.         while(i<=haystack.length()-needle.length())
  13.         {
  14.             f=true;
  15.             int j=i+needle.length()-1;
  16.             if(haystack[i]==needle[0] && haystack[j]==needle[needle.length()-1])
  17.             {
  18.                 int a=i+1;
  19.                 int k=1;
  20.        
  21.                 while(a<=j-1)
  22.                 {
  23.                     if(haystack[a]!=needle[k])
  24.                     {
  25.                         f=false;
  26.                         break;
  27.                     }
  28.                     a++;
  29.                     k++;
  30.                 }
  31.                if(f)
  32.                 {
  33.                     pos=i;
  34.                     f=true;
  35.                     break;
  36.                 }
  37.             }
  38.             f=false;
  39.            
  40.             i++;
  41.         }
  42.         if(f)
  43.         {
  44.             return pos;
  45.         }
  46.         else
  47.         {
  48.             return -1;
  49.         }
  50.        
  51.     }
  52. };
Advertisement
Add Comment
Please, Sign In to add comment