Loading

28. 实现strStr()

题目

 

代码

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(haystack.size()==0&&needle.size()==0)
            return 0;
        if(needle.size()==0)
            return 0;
        for(int i=0;i<haystack.size();i++)
        {
           
            if(haystack[i]==needle[0])
            {
                 bool isCom=true;
                 int temp=i;
                 for(int j=0;j<needle.size();j++)
                 {
                     if(temp>=haystack.size())
                         return -1;
                    if(haystack[temp++]!=needle[j])
                    {
                        isCom=false;
                    }
                 }
              
                if(isCom)
                {
                    return i;
                }
            }
        }
        return -1;
    }
};

 

思路

选择最简单的判断是否存在的方法,注意一些边界条件即可。

posted @ 2018-09-14 08:18  李正浩  阅读(101)  评论(0编辑  收藏  举报