LeetCode之Implement strStr()(Kotlin)

156 阅读1分钟

问题:


方法: 很简单的题目,遍历遇到相符起始字符逐个匹配,最后输出结果即可

package com.eric.leetcode

class ImplementStrStr {
    fun strStr(haystack: String, needle: String): Int {
        if (needle.isEmpty()) {
            return 0
        }
        loop@ for (el in haystack.withIndex()) {
            if (el.value == needle[0]) {
                for (index in needle.indices) {
                    if (el.index + index > haystack.lastIndex && needle[index] != haystack[el.index + index]) {
                        continue@loop
                    }
                }
                return el.index
            }
        }
        return -1
    }
}

有问题随时沟通

具体代码实现可以参考Github