i'm currently trying to solve a problem by counting the repeated sequences of character for example:- input:"aaabbcc" output should be printed as 3; input:"aabbcde" output:2. even if a repeated sequencce occurs two or more time it should be considered as 1?
private int stringocc1(String m) {
int count=0;
for (int i = 0; i < m.length(); i ) {
for (int j = 0; j < m.length(); j ) {
if(m.charAt(i)==m.charAt(j)) {
count ;
}
}
}
return count;
}
CodePudding user response:
import java.util.*;
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
Map<Character, Integer> sequences = new HashMap<>();
String input = "aabbcdeaa";
for (Character character : input.toCharArray()) {
if (!sequences.containsKey(character)) {
sequences.put(character, 0);
} else {
sequences.put(character, 1);
}
}
Long countOfSequences = sequences.entrySet().stream().filter(e -> e.getValue() == 1).count();
System.out.println("Sequences: " countOfSequences);
}
}
Output: 2 (so it counts separate sequences of the same character as one sequence, as per your requirement).
You can use a Hashmap to store each different character of the string and a value associated to it (0 if it's present once, 1 if it's present multiple times; this could be any value though, you could for example have it be the number of times each character appears if you needed that value as well), then filter the HashMap and count how many entries have a value different from zero.
CodePudding user response:
Here is one way to do it using regular expressions.
String [] testData = {"aabbccddefghh", "aabb", "aab", "aaabbbaaa",
"abcdeggggdddee", "abcdefg"};
for (String s : testData) {
System.out.println(s " -> " stringocc1(s));
}
prints
aabbccddefghh -> 5
aabb -> 2
aab -> 1
aaabbbaaa -> 3
abcdeggggdddee -> 3
abcdefg -> 0
(\\w )\\1
- says match any thing that has a character followed one or more of the same character. The\\1
is a backreference to the capture group in()
.find()
- keeps searching until it returns false- use
group()
to get the match. - then the
count
is returned.
private static int stringocc1(String m) {
int count = 0;
Matcher matcher = Pattern.compile("(\\w)\\1 ").matcher(m);
while (matcher.find()) {
count ;
}
return count;
}
You can also do it with a single loop.
- assign the first character to
c
- iterate over the loop and checking if a different character is seen
- then compare the
starting and ending
locations to see if thelength > 1
- and bump the count accordingly.
- then return the
count
.
Note: If the string ends in a sequence, the loop will terminate without adjusting the count. So this needs to be done prior to returning.
private static int stringocc1(String m) {
int count = 0;
char [] chars = m.toCharArray();
char c = chars[0];
int k = 0;
int i = 1;
for (; i < chars.length; i ) {
if (chars[i] != c) {
if (i - k > 1) {
count ;
}
c = chars[i];
k = i;
}
}
return count ((i-k > 1) ? 1 : 0);
}