[leetcode]28. Implement strStr()

    xiaoxiao2021-12-02  19

    题目链接:https://leetcode.com/problems/implement-strstr/

    Implement strStr().

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

    方法1:

    class Solution { public: int strStr(string haystack,string needle) { int m=(int)haystack.length(); int n=(int)needle.length(); for(int i=0;i<=m-n;i++) { int j; for(j=0;j<n;j++) { if(haystack[i+j]!=needle[j]) break; } if(j==n) return i; } return -1; } };

    方法2:

    class Solution{ public: int strStr(string haystack,string neddle) { int m=haystack.length(); int n=neddle.length(); if(m<n) return -1; for(int i=0;i<=m-n;i++) { if(haystack.substr(i,n)==neddle) return i; } return -1; } };

    转载请注明原文地址: https://ju.6miu.com/read-679728.html

    最新回复(0)