一个由小写英文字母组成的字符串s,长度不超过100。一个英文单词w,长度不超过10。 计算出使用s中的字符可以构造出w的数量。 例如:字符串S: axidpmlximppskdlsma目标单词w: map 字符串s中可以组成2个map。写出java代码
时间: 2024-04-16 22:24:23 浏览: 182
Sure! Here's an example of Java code that calculates the number of times the word 'w' can be constructed using the characters from string 's':
```java
import java.util.HashMap;
import java.util.Map;
public class WordConstructionCount {
public static int countWordConstruction(String s, String w) {
Map<Character, Integer> sCharCount = new HashMap<>();
Map<Character, Integer> wCharCount = new HashMap<>();
// Count the characters in string 's'
for (char c : s.toCharArray()) {
sCharCount.put(c, sCharCount.getOrDefault(c, 0) + 1);
}
// Count the characters in word 'w'
for (char c : w.toCharArray()) {
wCharCount.put(c, wCharCount.getOrDefault(c, 0) + 1);
}
int count = Integer.MAX_VALUE;
// Check if the characters in 'w' are available in 's' and calculate the minimum count
for (char c : wCharCount.keySet()) {
if (!sCharCount.containsKey(c)) {
return 0; // Character in 'w' is not present in 's'
}
int charCountInS = sCharCount.get(c);
int charCountInW = wCharCount.get(c);
count = Math.min(count, charCountInS / charCountInW);
}
return count;
}
public static void main(String[] args) {
String s = "axidpmlximppskdlsma";
String w = "map";
int result = countWordConstruction(s, w);
System.out.println("The number of times word 'w' can be constructed using characters from string 's': " + result);
}
}
```
In this code, we use two hash maps to count the occurrences of each character in string 's' and word 'w'. Then, we iterate through the characters in 'w' and check if they are present in 's'. Finally, we calculate the minimum count of each character in 's' divided by its count in 'w' to get the total number of times 'w' can be constructed.
阅读全文