📜  打印字符串所有重复字符的Java程序

📅  最后修改于: 2021-09-03 04:13:30             🧑  作者: Mango

给定一个字符串,任务是编写Java程序以打印所有重复字符的频率。

例子:

方法:想法是使用 HashMap 进行散列。

  • 创建一个{char, int}类型的 hashMap。
  • 遍历字符串,检查hashMap 是否已经包含遍历的字符。
  • 如果存在,则增加计数,否则以频率 = 1 在哈希图中插入字符。
  • 现在通过HashMap和外观的字符频率跨越不止1各自的频率打印这些字符。

下面是上述方法的实现:

Java
// Java program for the above approach
import java.util.*;
class GFG {
  
    // Function to print all duplicate
    // characters in string using HashMap
    public static void
    countDuplicateCharacters(String str)
    {
  
        // Creating a HashMap containing char
        // as a key and occurrences as a value
        Map map
            = new HashMap();
  
        // Converting given string into
        // a char array
        char[] charArray = str.toCharArray();
  
        // Checking each character
        // of charArray
        for (char c : charArray) {
  
            if (map.containsKey(c)) {
  
                // If character is present
                // in map incrementing it's
                // count by 1
                map.put(c, map.get(c) + 1);
            }
            else {
  
                // If character is not present
                // in map putting this
                // character into map with
                // 1 as it's value.
                map.put(c, 1);
            }
        }
  
        // Traverse the HashMap, check
        // if the count of the character
        // is greater than 1 then print
        // the character and its frequency
        for (Map.Entry entry :
             map.entrySet()) {
  
            if (entry.getValue() > 1) {
                System.out.println(entry.getKey()
                                   + " : "
                                   + entry.getValue());
            }
        }
    }
  
    // Driver Code
    public static void
    main(String args[])
    {
        // Given String str
        String str = "geeksforgeeks";
  
        // Function Call
        countDuplicateCharacters(str);
    }
}


输出:
s : 2
e : 4
g : 2
k : 2

时间复杂度: O(N)
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live