Following is what I end up doing but i did not find right answer.
Example - If I have the sequence "hellloo" the output will be "lll". Please tell me what is wrong?
public class LongestSequenceOfChar {
static String testcase1="hellloo";
public static void main(String[] args) {
LongestSequenceOfChar test = new LongestSequenceOfChar();
String result = test.longestSequenceOfChar(testcase1);
System.out.println(result);
}
public String longestSequenceOfChar(String str){
String result="";
for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
for(int j=i+1;j<str.length();j++){
char ch1=str.charAt(j);
if(ch!=ch1){
continue;
}
result+=ch;
}
}
return result;
}
}
You should have a counter that counts the number of the longest sequence for now. When you find a longer sequence, you should reset result
and update the counter accordingly.
However, you can have better solutions:
char
in it you add 1 in the corresponding cell in the helper array.HashMap
that has the char
as a key and the number it appears as the value. If it's a new char
you simply put it with 0 value, if it exists, you increment the existing value.Tip: Use a debugger, it can save your life.
1. Create a HashMap<Character,Integer>.. Integer-->count
2. Start from the beginning of your String.. For each character, check if it is already present in the hashmap
a. If Yes, just increment the count
b. if No, then add the character as key to the Map and set its count value to 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With