Warning: The magic method InvisibleReCaptcha\MchLib\Plugin\MchBasePublicPlugin::__wakeup() must have public visibility in /home/c9332742/public_html/bb-engineer.com/wp-content/plugins/invisible-recaptcha/includes/plugin/MchBasePublicPlugin.php on line 37
LeetCode解説 一日一問 28. Find the Index of the First Occurrence in a String | B-LOG

LeetCode解説 100本ノック 【Day13 Find the Index of the First Occurrence in a String】

LeetCode

LeetCodeって?

LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

LeetCodeとは、アルゴリズムやデータ構造を実践を通して学べる海外のプログラミング学習サイトです。

2022年12月現在2,000問を超える問題が登録されています。

各問題では、特定の入力をしたときに特定の返り値を出力する関数を作成することを求められます。

正誤判定は自動で行われます。

使用できる言語は、C++、C#、JAVA、Python3、Go、JSなど19言語が用意されています。

私はPython3で解いています。


Pythonではじめるアルゴリズム入門 伝統的なアルゴリズムで学ぶ定石と計算量 [ 増井 敏克 ]

問題

Find the Index of the First Occurrence in a String - LeetCode
Can you solve this real interview question? Find the Index of the First Occurrence in a String - Given two strings needle and haystack, return the index of the ...

タイトル:28. Find the Index of the First Occurrence in a String

難易度:Medium

内容:

文字列 haystack と needle が与えられる。
haystack 中で、needle が出現するインデックスを返す。
見つからない場合-1を返す。

例:

Input: haystack = "sadbutsad", needle = "sad"
Output: 0
※"sad"が1文字目から現れているので1文字目のインデックスを返す。
 2回以上 needle が表れている場合、1度目のほうのインデックスを返す。
Input: haystack = "leetcode", needle = "leeto"
Output: -1


回答

find メソッドを使うと1行で終わります。

return haystack.find(needle)


せっかくなので find メソッドを実装してみます。

for i in range(len(haystack) - len(needle) + 1):
    if haystack[i : i + len(needle)] == needle:
        return i
    return -1


いずれにしろ簡単ですね。


コード

コード全文です。

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        for i in range(len(haystack) - len(needle) + 1):
            if haystack[i : i + len(needle)] == needle:
                return i
        return -1


コードはgithubにも保管しています。

GitHub - BB-engineer/LeetCode
Contribute to BB-engineer/LeetCode development by creating an account on GitHub.


結果

いまいちLeetCodeの難易度設定が分かりません。。

コメント

タイトルとURLをコピーしました