STRSTRを実装28()実装はstrstr()]

説明

STRSTR()関数を実現します。
ストリング針干し草の山列が与えられると、針の位置は、干し草の山の文字列内の文字列(0から始まる)の最初の出現を検索します。ない場合は、-1を返します。


ここに画像を挿入説明
のアイデア

答え

  • パイソン
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        
        len1=len(haystack)
        len2=len(needle)
     # i+len2-1=len1-1---i==len1-len2--i<len1-len2+1
        for i in range(len1-len2+1):
            if haystack[i:i+len2]==needle:
                return i
        return -1
  • C ++
class Solution {
public:
    int strStr(string haystack, string needle) {
        int len1=haystack.size(),len2=needle.size();
          // i+len2-1=len1-1---i==len1-len2--i<len1-len2+1
        for (int i=0; i<len1-len2+1; i++)
            if (haystack.substr(i,len2)==needle)
                return i;
        return -1;
    }
};
公開された78元の記事 ウォン称賛7 ビュー10000 +

おすすめ

転載: blog.csdn.net/puspos/article/details/103152500