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

79 阅读1分钟

第四章 字符串* part02*

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

题目 链接 : leetcode.cn/problems/fi…

暴力法

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;
    }
};