**第四章 字符串****part02**

发布时间 2023-12-08 18:13:47作者: 晴夜空

第四章 字符串**part02**

 

 

 

 

28.找出字符串中第一个匹配项的下标

 

题目 链接 : https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/

 

 

暴力法

Code :

class Solution {
public:
   int strStr(string haystack, string needle) {
       //int len_haystack = strlen(haystack) ;
       int len_haystack = haystack.length() ;
       int len_needle = needle.length() ;

       int i = 0 ;
       int j = 0 ;

       if(len_needle > len_haystack )
      {
           cout<<"Error : strStr len_needle > len_haystack "<<endl;
           return -1 ;
      }

       if(len_needle == 0)
      {
           return 0 ;
      }

       for(i = 0 ; i < ((len_haystack )-(len_needle - 1) ) ; i++ )
      {
           //注意 进行 初始化
           for(j = 0 ;j < len_needle ; j++ )
          {
               if(haystack[i + j] != needle[ j ])
              {
                   break;

              }

          }

           if(j == len_needle)
          {
               return i;
          }

           //注意 此时 i 变量 还 没有 自增

      }




       return -1;
  }
};