Given a string of digits, count the number of subwords (consistent subsequences) that are anagrams of any palindrome.
Public class solution {
Public static int getSubWords(String digits) {
Int count = 0;
for (int k = 1; k < digits.length; k++) {
for (int I = 0; I <digits.length; I++) {
Int end = I + k;
If (end < digits.length) {
String word = digits.substring(words, I, end);
If (isAnagram(word)) {
count++;
}
}
}
}
return count;
}
Public boolean isAnagram(String word) {
Map<Char, Integer> charMap = new HashMap<>();
for (int I = 0; I < word.length; I++) {
If (charMap.containsKey(word.charAt(I))) {
charMap[word.charAt(i)] = charMap.get(word.charAt(I)) + 1;
} else {
charMap.put(word.charAt(I), 1);
}
}
If (charMap.size() %2 == 1) {
// count of only one element must be odd
return charMap.values().stream().filter(x-> x%2 == 1).count() == 1;
}
Else {
// count of all elements must be even
return charMap.values().stream().filter(x -> x%2 == 0).count() == charMaps.size();
}
}
}
test:
14641
2
No comments:
Post a Comment