LeetCode 1520: Maximum Number of Non-Overlapping Substrings Solution
Master LeetCode problem 1520 (Maximum Number of Non-Overlapping Substrings), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation:
To solve this problem, we can use a greedy approach combined with interval merging. We will iterate over the string to find the valid substrings by keeping track of the first and last occurrence of each character in the string. Then, we will merge overlapping intervals to form non-overlapping substrings.
- Iterate over the string to find the first and last occurrence of each character.
- Expand the intervals to cover all characters within the range.
- Merge overlapping intervals to create non-overlapping substrings.
- Choose the substrings with the minimum total length.
Time Complexity: O(N), where N is the length of the input string. Space Complexity: O(N)
:
Solution Code
class Solution {
public List<String> maxNumOfSubstrings(String s) {
List<String> result = new ArrayList<>();
Map<Character, Integer> first = new HashMap<>();
Map<Character, Integer> last = new HashMap();
// Find first and last occurrence of each character
for (int i = 0; i < s.length(); i++) {
last.put(s.charAt(i), i);
}
for (int i = s.length() - 1; i >= 0; i--) {
first.put(s.charAt(i), i);
}
int end = -1, start = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (i == first.get(c)) {
int newEnd = findEnd(s, i, first, last);
if (newEnd != -1 && i > end) {
end = newEnd;
result.add("");
}
}
if (i == last.get(c) && i == end) {
result.set(result.size() - 1, s.substring(start, end + 1));
start = i + 1;
}
}
return result;
}
private int findEnd(String s, int i, Map<Character, Integer> first, Map<Character, Integer> last) {
int end = last.get(s.charAt(i));
for (int j = i; j <= end; j++) {
if (first.get(s.charAt(j)) < i) {
return -1;
}
end = Math.max(end, last.get(s.charAt(j)));
}
return end;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1520 (Maximum Number of Non-Overlapping Substrings)?
This page provides optimized solutions for LeetCode problem 1520 (Maximum Number of Non-Overlapping Substrings) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1520 (Maximum Number of Non-Overlapping Substrings)?
The time complexity for LeetCode 1520 (Maximum Number of Non-Overlapping Substrings) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1520 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1520 in Java, C++, or Python.