Leetcode 2287. Rearrange Characters to Make Target String
You are given two strings: s
and target
. You are supposed to rearrange the characters of s
to create as many target strings as possible.
Input: s = "ilovecodingonleetcode", target = "code"
Output: 2
Explanation: You can create two "code" strings from the given string.
s
and target
case-sensitive?
s
and target
?
s
and target
?
s
and target
have a length between 1 and 1000.To determine the number of times we can rearrange the characters of s
to create the target
string:
s
and target
.target
, check how many times it can appear given the counts in s
.target
strings that can be formed.Here’s the implementation in Java:
import java.util.HashMap;
public class RearrangeCharacters {
public int rearrangeCharacters(String s, String target) {
// Frequency map for the characters in the string s
HashMap<Character, Integer> sCount = new HashMap<>();
for (char ch : s.toCharArray()) {
sCount.put(ch, sCount.getOrDefault(ch, 0) + 1);
}
// Frequency map for the characters in the target string
HashMap<Character, Integer> targetCount = new HashMap<>();
for (char ch : target.toCharArray()) {
targetCount.put(ch, targetCount.getOrDefault(ch, 0) + 1);
}
// Calculate the maximum number of times we can form the target string
int maxCount = Integer.MAX_VALUE;
for (char ch : targetCount.keySet()) {
if (sCount.containsKey(ch)) {
maxCount = Math.min(maxCount, sCount.get(ch) / targetCount.get(ch));
} else {
return 0; // If the character is not in s, we cannot form the target at all
}
}
return maxCount;
}
public static void main(String[] args) {
RearrangeCharacters rc = new RearrangeCharacters();
System.out.println(rc.rearrangeCharacters("ilovecodingonleetcode", "code")); // Output: 2
System.out.println(rc.rearrangeCharacters("abcba", "abc")); // Output: 1
System.out.println(rc.rearrangeCharacters("abbaccaddaeea", "aaaaa")); // Output: 1
}
}
The time complexity of this solution is O(n + m), where n
is the length of the string s
and m
is the length of the string target
. This is because we iterate through each character of s
and target
only once to build the frequency maps and then process those maps.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?