leetcode 28. Implement strStr()

来源:互联网 发布:js隐藏滚动条 编辑:程序博客网 时间:2024/06/06 18:04

Implement strStr().

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

strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串,我这里是直接循环判断的。

代码如下:

public class Solution {    public int strStr(String haystack, String needle)     {        //考虑特殊情况        if(haystack==null||needle==null || haystack.length() < needle.length())            return -1;        int res=-1;        for(int i=0;i<haystack.length()-needle.length()+1;i++)        {            int j=0;            for(;j<needle.length();j++)            {                if(needle.charAt(j)!=haystack.charAt(i+j))                    break;            }            if(j==needle.length())            {                res=i;                break;            }        }        return res;    }    public static void main(String[] args)    {        new Solution().strStr("a", "a");    }} 

下面是C++的做法,我这里直接使用了C++的库函数,

代码如下:

#include <iostream>#include <string>using namespace std;class Solution {public:    int strStr(string haystack, string needle)    {        int res = haystack.find(needle);        return res == string::npos ? -1 : res;    }};