美文网首页
LeetCode之Longest Common Prefix(K

LeetCode之Longest Common Prefix(K

作者: 糕冷羊 | 来源:发表于2021-10-18 19:46 被阅读0次

    问题:



    方法:
    逐个比较字符串的最长公共前缀,复杂度O(m*n)。

    package com.eric.leetcode
    
    class LongestCommonPrefix {
        fun longestCommonPrefix(strs: Array<String>): String {
            if (strs.isEmpty()) {
                return ""
            }
            if (strs.size == 1) {
                return strs[0]
            }
            return lcp(strs[0], 1, strs)
        }
    
        private fun lcp(s1: String, cur: Int, strs: Array<String>): String {
            val s2 = strs[cur]
            var index = 0
            var commonPrefix = "";
            while (index <= s1.lastIndex && index <= s2.lastIndex) {
                if (s1[index] == s2[index]) {
                    commonPrefix += s1[index]
                } else {
                    break
                }
                index++
            }
            if (cur == strs.lastIndex) {
                return commonPrefix
            }
            return lcp(commonPrefix, cur + 1, strs)
        }
    }
    

    有问题随时沟通

    具体代码实现可以参考Github

    相关文章

      网友评论

          本文标题:LeetCode之Longest Common Prefix(K

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