gpt4 book ai didi

java - 字串中的字数

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:01:04 25 4
gpt4 key购买 nike

我有一个特殊情况(希望保持较低的时间复杂度)我需要计算可以从给定字符串创建单词的次数。我下面的代码只设法得到它一次,如果可以多次创建单词失败。有什么想法吗?

//String that needs to be searched
String s= "ccoptarra";

//Words that need to be found
String[] words = { "car", "pot", "bag" };

ArrayList count = new ArrayList();
HashMap map = new HashMap();
for (int i = 0; i < words.length; i++) {
count.add(0);
String w = words[i];
map.put(w, "");
for (int j = 0; j < w.length(); j++) {
if (s.contains(String.valueOf(w.charAt(j)))) {
map.put(w, map.get(w).toString() + w.charAt(j));
if (map.get(w).equals(w))
count.add(i, ((int)count.get(i)) + 1);
}
}
}
for (int i = 0; i < count.size(); i++)
System.out.println("Word: " + words[i] + ", count = " + count.get(i));

输出:

Word: car, count = 1
Word: pot, count = 1
Word: bag, count = 0

最佳答案

您可以使用Map来保存每个字符和字符数。之后,只需循环测试单词并从 map 中为该单词选择最少的字符数。这是代码

        //String that needs to be searched
String s= "ccoptarra";

//Words that need to be found
String[] words = {"car","pot","bag"};

List<Integer> count = new ArrayList<Integer>();
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i=0; i<s.length();i++) {
char c = s.charAt(i);
if (map.get(c) != null) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}

for (int i=0; i<words.length; i++) {
int min = Integer.MAX_VALUE;
for (int j=0; j<words[i].length(); j++) {
Integer value = map.get(words[i].charAt(j));
if (value == null) {
min = 0;
} else if (value < min) {
min = value;
}
}
count.add(min == Integer.MAX_VALUE ? 0 : min);
}

for(int i=0; i<count.size(); i++)
System.out.println("Word: "+words[i]+", count = "+count.get(i));

关于java - 字串中的字数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35433626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com