-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathLongestHappyPrefix.py
More file actions
61 lines (43 loc) · 1.22 KB
/
LongestHappyPrefix.py
File metadata and controls
61 lines (43 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""
Here: 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.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 105
s contains only lowercase English letters.
"""
def longestPrefix(s: str) -> str:
n = len(s)
for i in range(n - 2, -1, -1):
prefix = s[:i + 1]
suffix = s[n - len(prefix):]
if prefix == suffix:
return prefix
return ''
if __name__ == "__main__":
# taking the input
s = input("Enter word: ")
print(longestPrefix(s))
"""
Inputs
s = "level"
Output: "l"
s = "ababab"
Output: "abab"
s = "leetcodeleet"
Output: "leet"
"""