Code11はstrStr()を実装します

トピック

leetcode28。strStr
()関数実装するためにstrStr()実装します。

干し草の山のひもと針のひもが与えられた場合、針の
ひもが干し草の山のひもに現れる最初の位置(0から始まる)を見つけます存在しない場合は-1が返されます。

例1:
入力:haystack = "hello"、needle = "ll"
出力:2

例2:
入力:haystack = "aaaaa"、needle = "bba"
出力:-1

説明:
針が空の文字列の場合、どの値を返す必要がありますか?これはインタビューの良い質問です。
この質問では、針が空の文字列の場合は0を返す必要があります。これ
、C言語のstrstr()およびJavaのindexOf()の定義と一致しています。

コード

// C
#include <string.h>
int strStr(char* haystack, char* needle) {
    
    
  if (needle == "") {
    
    
    return 0;
  }

  int haystack_len = strlen(haystack);
  int needle_len= strlen(needle);
  char* temp = needle;
  for (int i = 0; i <= haystack_len - needle_len; ++i){
    
    
    int j = i;
    int k = 0;
    while((k < needle_len) && (haystack[j] == needle[k])){
    
    
      ++j;
      ++k;
    }

    if (k == needle_len){
    
    
      return i;
    }
  }

  return -1;
}

// C++
#include <string>
using namespace std;
class Solution {
    
    
 public:
  int strStr(string haystack, string needle) {
    
    
    if (needle.empty()) {
    
    
      return 0;
    }
    auto it = haystack.find(needle);
    if (it == string::npos) {
    
    
      return -1;
    } else {
    
    
      return it;
    }
  }
};

テスト

#include <iostream>

int main() {
    
    
  {
    
    
    // C
    char* haystack = "hello";
    char* needle = "lo";
    cout << strStr(haystack, needle) << endl;
  }
  {
    
    
    // C++ 
    string haystack = "hello";
    string needle = "ll";
    Solution s;
    cout << s.strStr(haystack, needle);
  }
  cin.get();
  return 0;
}
  • 結果
3
2

おすすめ

転載: blog.csdn.net/luoshabugui/article/details/109537943
おすすめ