I solved a problem recently and I want to check the code I have written is good or is a bad design. Is good or poor in terms of efficiency. The problem is given an input string count the number of occurrence of each character in the string and print it, example:
Input String is: fffdddssaaa
Result is f3d3s2a3
My Program:
public class StringCount {
static String process(String s) {
System.out.println("Input String is: " + s);
char[] array = s.toCharArray();
int j = 0;
int m = 0;
int i = 0;
int t = 0;
int count = 0;
StringBuilder str = new StringBuilder();
for (j = 0; j < s.length(); j++) {
m = 0;
for (i = 0; i < s.length(); i++) {
if (array[j] == array[i]) {
m++;
}
}
//System.out.println("char " + array[j] + " is " + m);
String ss = str.toString();
char[] temp = ss.toCharArray();
if (count == 0) {
str.append(array[j]);
str.append(m);
ss = str.toString();
temp = ss.toCharArray();
count++;
} else if (count > 0) {
if (temp[t] == array[j]) {
} else {
str.append(array[j]);
str.append(m);
ss = str.toString();
temp = ss.toCharArray();
t = t + 2;
}
}
}
System.out.println("Result is " + str);
return str.toString();
}
public static void main(String[] args) {
process("fffdddssaaa");
}
}
Please provide your valuable reviews of this code. Thanks
HashMap
? – PM 77-1 Oct 6 at 18:55