Leetcode Day 文字列内の最初に出現するインデックスを見つける日の説明

王林
リリース: 2024-07-18 14:51:47
オリジナル
442 人が閲覧しました

Leetcode Day Find the Index of the First Occurrence in a String Explained

The problem is as follows:

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
ログイン後にコピー

Example 2:

Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.
ログイン後にコピー

This is how I solved it:

This is the first easy problem that was actually easy. Just use the built-in index() function, and that's it!
This is how it works:

  • Check if 'needle' is a substring of 'haystack'
  • If it is, return the index of the first occurrence of 'needle'
  • Else if 'needle' is not found, return -1
if needle in haystack:
    return haystack.index(needle)
else:
    return -1
ログイン後にコピー

This is the completed solution:

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        return haystack.index(needle) if needle in haystack else -1
ログイン後にコピー

以上がLeetcode Day 文字列内の最初に出現するインデックスを見つける日の説明の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!