Reputation: 25
Is there any utility method in java to find the repeating duplicate character in java?
e.g. "allowed" is not allowed as it has two repeating 'l' and "repeating" is allowed though it has two 'e'
I was looking at the StringUtils
, but doesn't have anything there. I am thinking to write something like
for (each char in string) {
if (char at counter of loop == char at next counter) {
break;
}}
Upvotes: 0
Views: 270
Reputation: 8032
You can try this a well:
package com.stack.overflow.works.main;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @author sarath_sivan
*/
public class DuplicatesFinder {
public static void findDuplicates(String inputString) {
Map<Character, Integer> duplicatesMap = new HashMap<Character, Integer>();
char[] charArray = inputString.toCharArray();
for (Character ch : charArray) {
if (duplicatesMap.containsKey(ch)) {
duplicatesMap.put(ch, duplicatesMap.get(ch) + 1);
} else {
duplicatesMap.put(ch, 1);
}
}
Set<Character> keySet = duplicatesMap.keySet();
for (Character ch: keySet) {
if (duplicatesMap.get(ch) > 1) {
System.out.println("[INFO: CHARACTER " + ch + " IS DUPLICATE, OCCURENCE: " + duplicatesMap.get(ch) + " TIMES]");
}
}
}
public static void main(String[] args) {
DuplicatesFinder.findDuplicates("sarath kumar sivan");
}
}
It will produce the simple test result for the input string "sarath kumar sivan" like this:
[INFO: CHARACTER IS DUPLICATE, OCCURENCE: 2 TIMES]
[INFO: CHARACTER s IS DUPLICATE, OCCURENCE: 2 TIMES]
[INFO: CHARACTER r IS DUPLICATE, OCCURENCE: 2 TIMES]
[INFO: CHARACTER a IS DUPLICATE, OCCURENCE: 4 TIMES]
Upvotes: -1
Reputation:
Try this:
Character last = null;
boolean allowed = true;
for (Character c : str.toCharArray()) {
if (c.equals(last)) {
allowed = false;
break;
}
last = c.charValue();
}
Upvotes: 0
Reputation: 328893
The loop approach is one solution or, if you want something fancy, you could use a regex approach, which would look like:
private static final Pattern repeatMatcher = Pattern.compile("^(?:(.)(?!\\1))*$");
public static boolean hasRepeatedCharacters(String input) {
return !repeatMatcher.matcher(input).matches();
}
But the basic approach with a loop is certainly more readable:
public static boolean hasRepeatedCharacters(String input) {
for (int i = 0; i < input.length() - 1; i++) {
if (input.charAt(i) == input.charAt(i + 1)) return true;
}
return false;
}
Upvotes: 3
Reputation: 2006
Doesn't sound like a common usecase for an utility. Your code logic seems good enough. Optimization to check if it's single char or not and check for char at next counter doesn't exceed string length should do.
Upvotes: 0
Reputation: 38444
There's no utility method for this as I don't think this problem is common enough to actually deserve one. It far too specific for any general use.
Make your own method just as you suggested, it seems fine.
Upvotes: 2