美文网首页
LeetCode之Implement strStr()(Kotl

LeetCode之Implement strStr()(Kotl

作者: 糕冷羊 | 来源:发表于2021-08-20 11:16 被阅读0次

    问题:



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

    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

    相关文章

      网友评论

          本文标题:LeetCode之Implement strStr()(Kotl

          本文链接:https://www.haomeiwen.com/subject/npqtiltx.html