leetcode-1520-Maximum Number of Non-Overlapping Substrings
问题
Given a string s
of lowercase letters, you need to find the maximum number of non-empty substrings of s
that meet the following conditions:
- The substrings do not overlap, that is for any two substrings
s[i..j]
ands[k..l]
, eitherj < k
ori > l
is true. - A substring that contains a certain character
c
must also contain all occurrences ofc
.
Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length.
Notice that you can return the substrings in any order.
Example 1:
1 | Input: s = "adefaddaccc" |
Example 2:
1 | Input: s = "abbaccd" |
Constraints:
1 <= s.length <= 10^5
s
contains only lowercase English letters.
分析
保存每个字符出现的最左端和最右端的下标。
- 如果是找到了一段合法的 substring,同时该 substring 中包含了更短的符合要求的 substring,则忽略掉长的substring。
- 如找到了 “abccba”,其中包含 “bccb”,又包含 “cc”,则保留 “cc” ,忽略其他。
- First, collect left (
l
) and right(r
) indices for every character. - Then, go through the string. If the current index
i
is the left index for the characterS[i]
, it may be a valid substring.- We then use a sliding window pattern to find the lendth of the substring.
- If we find a character that appears before
i
- we do not have a valid string starting ati
.
- If we find a character that appears before
- If substring is valid, we remember it, as well as it’s right edge.
- This logic, repeated, will ensure that we find the valid substring with the smallest right edge.
- We then use a sliding window pattern to find the lendth of the substring.
- If the valid substring starts after the previous right edge, there is no overlap. The previous substring should be included into the result.
最快情况下查找26次字串,每一次查找的时间复杂度是 $O(n)$ ,因此整体的时间复杂度是 $O(n)$ 。
空间复杂度,只用额外空间记录了每个字符最左端和最右端的下标,因此时间复杂度是 $O(1)$。
代码
1 | class Solution { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/07/20/leetcode-1520/
License: 知识共享署名-非商业性使用 4.0 国际许可协议