Java程序查找具有重复计数的字符串中的重复字符
时间:2020-01-09 10:35:33 来源:igfitidea点击:
编写Java程序以在字符串中查找重复次数众多的采访中重复的字符。这篇文章提供了两种方法来编写此问题的程序。
1我们可以使用HashMap在字符串中查找重复字符以及重复计数。
2如果要求我们不使用任何内置结构或者API,则可以编写逻辑以使用for循环在String中查找重复字符。
使用HashMap在String Java程序中查找重复的字符
在HashMap中,我们可以通过以下方式存储每个字符:该字符成为键,并且计数为值。对于每个字符,请在HashMap中检查char是否已经存在;如果是,则为现有字符增加计数,如果否,则将字符添加到HashMap中,初始计数为1.
public class DuplicateChars {
public static void main(String[] args) {
findDuplicateChars("How many duplicates in this string");
findDuplicateChars("Addis Ababa");
}
private static void findDuplicateChars(String str) {
System.out.println("Duplicates in- "+ str);
char[] strArr = str.toCharArray();
Map<Character, Integer> charMap = new HashMap<>();
for(char c : strArr) {
// Ignore spaces
if(c == ' ')
continue;
// check if character already exists
if(charMap.containsKey(c)) {
charMap.put(c, charMap.get(c) + 1);
}else {
charMap.put(c, 1);
}
}
// Iterating collection view of the Map
Set<Map.Entry<Character, Integer>> countSet = charMap.entrySet();
for(Map.Entry<Character, Integer> entry : countSet){
if(entry.getValue() > 1) {
System.out.println(entry.getKey() + " found " + entry.getValue() + " times");
}
}
}
}
输出:
Duplicates in- How many duplicates in this string a found 2 times i found 4 times n found 3 times s found 3 times t found 3 times Duplicates in- Addis Ababa A found 2 times a found 2 times b found 2 times d found 2 times
使用循环在String Java程序中查找重复字符
如果我们需要编写逻辑来自己查找重复项,则可以使用外部和内部for循环来执行此操作。在外循环中,一次将String迭代一次,然后在内循环中,对String扫描相同的字符。如果找到它的增量计数。
public class DuplicateChars {
public static void main(String[] args) {
findDuplicateChars("How many duplicates in this string");
findDuplicateChars("Addis Ababa");
}
private static void findDuplicateChars(String str) {
System.out.println("Duplicates in- "+ str);
int count;
for(int i = 0; i < str.length(); i++) {
// get a character
char c = str.charAt(i);
//starting count for any character
count = 1;
//ignore spaces
if(c == ' ')
continue;
for(int j = i + 1; j < str.length(); j++) {
if(c == str.charAt(j)) {
count++;
// remove the char which is already counted
str = str.substring(0, j) + str.substring(j+ 1);
}
}
if(count > 1) {
System.out.println(c + " found " + count + " times");
}
}
}
}

