静态字符串中的字符数

时间:2014-09-02 01:32:14

标签: java string count

我有一个代码可以告诉我字符串中出现次数最多的字符。 cade如下:

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map;
public class MaximumOccurringChar {

    static final String TEST_CASE_1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today. Help!";
public static void main(String[] args) {

        MaximumOccurringChar test = new MaximumOccurringChar();
        List<Character> result = test.maximumOccurringChars(TEST_CASE_1, true);
        System.out.println(result);
    }


    public List<Character> maximumOccurringChars(String str) {
        return maximumOccurringChars(str, false);
    }

    // set skipSpaces true if you want to skip spaces
    public List<Character> maximumOccurringChars(String str, Boolean skipSpaces) {
        Map<Character, Integer> map = new HashMap<>();
        List<Character> occurrences = new ArrayList<>();
        int maxOccurring = 0;

        // creates map of all characters
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            if (skipSpaces && ch == ' ')      // skips spaces if needed
                continue;

            if (map.containsKey(ch)) {
                map.put(ch, map.get(ch) + 1);
            } else {
                map.put(ch, 1);
            }

            if (map.get(ch) > maxOccurring) {
                maxOccurring = map.get(ch);         // saves max occurring
            }
        }

        // finds all characters with maxOccurring and adds it to occurrences List
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            if (entry.getValue() == maxOccurring) {
                occurrences.add(entry.getKey());
            }
        }

        return occurrences;
    }
}

但我无法弄清楚如何显示他们的数量。例如,如果我输入“aasssddeefgt”,它表示s发生的次数最多,但它并没有告诉我它发生了3次。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

我建议您首先创建一种方法来计算charString的出现次数,

static int countOccurences(String in, char ch) {
    int count = 0;
    if (in != null) {
        for (char c : in.toCharArray()) {
            if (ch == c) {
                count++;
            }
        }
    }
    return count;
}

接下来,我要创建一个通用的Comparable Tuple POJO(类似) -

static class Tuple<K, V extends Comparable<V>> implements
        Comparable<Tuple<K, V>> {
    private K ch;
    private V count;

    public Tuple(K ch, V count) {
        this.ch = ch;
        this.count = count;
    }

    @Override
    public int compareTo(Tuple<K, V> o) {
        return o.count.compareTo(this.count);
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Tuple) {
            return this.ch.equals(((Tuple) o).ch);
        }
        return false;
    }

    @Override
    public String toString() {
        return String.format("'%s' = %d", ch.toString(), count);
    }
}

然后我们可以创建Tuple<Character, Integer> List之类的

static List<Tuple<Character, Integer>> getTuples(String in) {
    List<Tuple<Character, Integer>> tuples = new ArrayList<>();
    // Only need to get each char count once.
    Set<Character> processed = new TreeSet<>();
    // to skip space(s)
    // processed.add(' '); // <-- add before the loop.
    for (char ch : in.toCharArray()) {
        if (processed.contains(ch)) {
            continue;
        }
        processed.add(ch);
        tuples.add(new Tuple<>(ch, countOccurences(in, ch)));
    }
    return tuples;
}

最后,我们可以从main()

中调用它(和Collections.sort()
public static void main(String[] args) {
    final String TEST_CASE_1 = "Hello! Are you all fine? What are u doing "
            + "today? Hey Guyz,Listen! I have a plan for today. Help!";
    List<Tuple<Character, Integer>> tuples = getTuples(TEST_CASE_1);
    Collections.sort(tuples);
    System.out.println(tuples);
}

输出(为此帖格式化)

[' ' = 18, 'e' = 8, 'a' = 8, 'l' = 6, 'o' = 6, 'y' = 5, 'n' = 4, 't' = 4, 
 'H' = 3, '!' = 3, 'r' = 3, 'u' = 3, 'i' = 3, 'd' = 3, 'f' = 2, '?' = 2,
 'h' = 2, 'p' = 2, 'A' = 1, 'W' = 1, 'g' = 1, 'G' = 1, 'z' = 1, ',' = 1,
 'L' = 1, 's' = 1, 'I' = 1, 'v' = 1, '.' = 1]

答案 1 :(得分:0)

将地图创建和max-occurrence字符分离为不同的方法可以解决问题。

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map;
public class MaximumOccurringChar {
static final String TEST_CASE_1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today. Help!";

public static void main(String[] args) {

    MaximumOccurringChar test = new MaximumOccurringChar();
    Map<Character, Integer> map = charMap(TEST_CASE_1, true);
    int max = max(map);
    for(Map.Entry<Character, Integer> e : map.entrySet()){
        if(e.getValue() == max)
            System.out.println(e.getKey() + " " + max);
    }
}

public static Map<Character, Integer> charMap(String s, boolean skipSpaces){
    Map<Character, Integer> map = new HashMap<>();
    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);

        if (skipSpaces && ch == ' ')      // skips spaces if needed
            continue;

        if (map.containsKey(ch)) {
            map.put(ch, map.get(ch) + 1);
        } else {
            map.put(ch, 1);
        }
    }
    return map;
}

public static int max(Map<Character, Integer> m){
    int max = Integer.MIN_VALUE;
    for(Integer i : m.values()){
        if(i > max)
            max = i;
    }
    return max;
}

}