【每日一题0731】实现strStr()

:woman_mage:已知两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。

示例:

输入:haystack = "hello", needle = "ll"
输出:2

题目难度:简单
题目来源:力扣(LeetCode)28

def strStr(haystack:str, needle:str) -> int:
    pass
    
assert strStr("hello", "ll") == 2
assert strStr("aaaaa", "bba") == -1
def strStr(haystack: str, needle: str) -> int:
    return haystack.find(needle)


assert strStr("hello", "ll") == 2
assert strStr("aaaaa", "bba") == -1
assert strStr("aabbasdbba", "bba") == 2
    public int strStr(ArrayList<String> haystack, ArrayList<String> needle) {
        int needleLength = needle.size();
        int haystackLength = haystack.size();
        int start = 0;
        int end = needleLength;
        while (end <= haystackLength) {
            if (haystack.subList(start, end).equals(needle)) {
                return start;
            } else {
                start++;
                end++;
            }
        }
        return -1;
    }
def strStr(haystack: str, needle: str) -> int:
    # haystack =  'llhelloll'
    # needle = 'lla'
    try:
        return haystack.index(needle)
    except ValueError as e:
        return -1

image

def strStr(haystack:str,needle:str)->int:
    return haystack.find(needle)
def strStr(haystack:str, needle:str) -> int:
    if needle in haystack:
        return haystack.index(needle)
    else:
        return -1
def strStr(haystack:str, needle:str) -> int:
    return haystack.find(needle)

assert strStr("hello", "ll") == 2
assert strStr("aaaaa", "bba") == -1
def strStr(haystack: str, needle: str) -> int:
    a = [i for i in range(len(haystack) - len(needle)) if haystack[i:i + len(needle)] == needle]
    if len(a) == 0:
        return -1
    else:
        return a[0]


assert strStr("hello", "ll") == 2
assert strStr("aaaaa", "bba") == -1

image