1392. Longest Happy Prefix

复制代码
package LeetCode_1392

/**
 * 1392. Longest Happy Prefix
 * https://leetcode.com/problems/longest-happy-prefix/
 *
 * A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.

Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel").
The largest prefix which is also suffix is given by "l".

Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
 * */
class Solution {
    /*
    * solution: KMP, find a prefix which also is a suffix,
    * Time complexity:O(n), Space complexity:O(n)
    * */
    fun longestPrefix(s: String): String {
        if (s == null || s.isEmpty()) {
            return ""
        }
        val lpsTable = createLPSTable(s)
        val last = lpsTable[lpsTable.lastIndex]
        return if (last == 0) "" else s.substring(0, last)
    }

    /**
     * Create LPS table or pi table
     * */
    private fun createLPSTable(string: String): IntArray {
        var i = 1//i for scan string
        var j = 0//j from scan patten
        val m = string.length
        val lps = IntArray(m)
        lps[0] = 0//lps[0] is always 0
        //loop for i = 1 to m-1
        while (i < m) {
            if (string[i] == string[j]) {
                //if two char are same, move i,j
                lps[i] = j + 1
                i++
                j++
            } else {
                /*
                * if not the same, 2 situation:
                * 1. if (j==0), then cannot move j to left, move i to right, and update lps[i]
                * 2. if (j>0), move j to table[j-1]
                * */
                if (j == 0) {
                    lps[i] = j
                    i++
                } else {
                    j = lps[j - 1]
                }
            }
        }
        return lps
    }
}
复制代码

Knuth-Morris-Pratt KMP String Matching Algorithm

posted @   johnny_zhao  阅读(100)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-11-03 266. Palindrome Permutation
点击右上角即可分享
微信分享提示