单词以字符串计数

时间:2016-02-16 13:14:52

标签: java algorithm time-complexity

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

//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));

OutPut:

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

2 个答案:

答案 0 :(得分:1)

您可以使用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));

答案 1 :(得分:0)

我将扩展我的推荐作为帮助您理解的答案:

步骤1:创建一些映射以计算字符数。

您可以使用带有字符编号的数组作为索引(减去&#39; a&#39;的值,将偏移量移至a = 0,b = 1等)。或者您可以使用Map<Character, Integer>

这应该导致:a = 2,c = 2,o = 1,p = 1,r = 2,t = 1

步骤2:对您要查找的每个字词重复步骤1,例如对于汽车,你得到a = 1,c = 1,r = 1(对于包你来说,你有a = 1,b = 1,g = 1)。

步骤3:对于搜索词中的每个字符,您可以计算出将字符所需的数字与可用数字(分数的整数部分)相匹配的频率,并获得所有字符的最小值。字。

示例:

  • car:a = 2/1 = 2,c = 2/1 = 2,r = 2/1 = 2 - >最低为2
  • bag:a = 2/1 = 2,b = 0/1 = 0,g = 0/1 = 0 - >最小值是0