Sundy算法 C++实现

class Solution3
{
public:
    int getIndexOf(string str,string match)
    {
        if(str.size()<1 || match.size()<1 || str.size()<match.size()) return -1;
        int R=match.size();
        int pos=0;
        for(int i=0;i<str.size();i++)
        {
            if(str[i]!=match[pos])
            {

                while(pos>0 && str[R]!=match[pos])
                {
                    pos--;
                }
                i=R-pos;
                pos=0;
                R=i+match.size();
            }else
            {
                if(pos==match.size()-1)
                {
                    return i-pos;
                }
                pos++;
            }
        }
        return -1;
    }
};

int main()
{
    string str = "abcabcababaccc";
    string match = "ababa";
    Solution3 ss;
    cout<<ss.getIndexOf(str,match)<<endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/csu_guo_liang/article/details/81176235