admin管理员组

文章数量:1636924

题目

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

分析

从一个字符串中查找给定字符串第一次出现的位置,C++的泛型算法里面find算法只能查找给定区间的某个元素出现位置,而search算法可以查找给定区间内某一区间第一次出现的位置,即前两个参数是haystack.begin()和haystack.end(),后两个是needle.begin()和needle.end(),但是search算法略慢,最快的是使用string.find(),该函数可在当前string中查找参数第一次出现的位置,如果找不到,则返回npos,方法一使用search实现,方法二使用string的find实现。

方法一:

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(haystack.empty()&&needle.empty())
            return 0;
        string::iterator it=search(haystack.begin(),haystack.end(),needle.begin(),needle.end());
        return it==haystack.end()?-1:it-haystack.begin();
    }
};
方法二:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int ans = haystack.find(needle);
        return (ans==string::npos) ? -1 : ans;
    }
};




本文标签: implementstrStr