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

王林
发布: 2024-07-18 14:51:47
原创
439 人浏览过

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 Find the Index of the First Occurrence in a String Explained的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!