LeetCode-Python-1392. The longest happy prefix (brute force method + string hash)

"Happy Prefix" is a string that is both a non-empty prefix and a suffix (excluding the original string itself) in the original string.

Give you a string s, please return its longest happy prefix.

If there is no prefix that satisfies the title, an empty string is returned.

 

Example 1:

Input: s = "level"
Output: "l"
Explanation: Excluding s itself, there are 4 prefixes ("l", "le", "lev", "leve") and 4 suffixes ("l", "el", "vel", "evel"). The longest string with both prefix and suffix is ​​"l".
Example 2:

Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the longest string that is both a prefix and a suffix. The title allows the prefix and suffix to overlap in the original string.
Example 3:

Input: s = "leetcodeleet"
Output: "leet"
Example 4:

Input: s = "a"
Output: ""
 

prompt:

1 <= s.length <= 10 ^ 5
s contains only lowercase English letters

Source: LeetCode
Link: https://leetcode-cn.com/problems/longest-happy-prefix The
copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.

The first idea:

After the violence was solved, I tried it out, but I could pass it!

Time complexity: O (N ^ 2)

Space complexity: O (N)

class Solution(object):
    def longestPrefix(self, s):
        """
        :type s: str
        :rtype: str
        """
        res = ""
        for i in range(len(s) -1, -1, -1):
            if s[:i] == s[-i:]:
                res = s[:i]
                break
        return res if res != s else ""

The second idea:

The algorithm on the string hash,

Convert each string to a number in P system, and then modulo M to calculate a hash value.

Through appropriate values ​​of P and M, each string and hash value should correspond to each other as much as possible, so that each time you compare numbers, you can know whether the strings are the same in O (1) time.

Here P = 131 and M = 10 ** 9 + 7.

1. In order to calculate the value of prefix,

Given that the hash value of s [: i] is h (i), then the hash value of s [: i + 1] is h (i + 1) = (h (i) * P + s [i])% M,

Similar to the decimal system, the current number is 56, and a new 3 is added to the far right. The result is (56 * 10 + 3)% 10 = 563.

2. In order to calculate the value of suffix, an additional variable multiple is needed to record the new highest multiple of base

suffix_new = (new letter * multiple + suffix_old)% M,

Similar to the decimal system, the current number is 34, and a new 2 is added to the leftmost side. It is known that the new 2 corresponds to a hundred digits.

So the result is (2 * 100 + 34)% 10 = 234

Time complexity: O (N)

Space complexity: O (1)

class Solution(object):
    def longestPrefix(self, s):
        """
        :type s: str
        :rtype: str
        """
        base = 131
        mod = 10 ** 9 + 7
        res = ""
        prefix, suffix = 0, 0
        multiple = 1
        for i in range(len(s) - 1):
            prefix = (prefix * base + ord(s[i])) % mod 
            suffix = (ord(s[-(i + 1)]) * multiple + suffix) % mod 
            if prefix == suffix:
                res = s[:i + 1]
            
            multiple = multiple * base % mod

        return res

 

Published 734 original articles · 121 praises · 210,000 views

Guess you like

Origin blog.csdn.net/qq_32424059/article/details/105139418
Recommended