Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return longest sequence of chars in a string in java?

Tags:

java

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;
    }
}
like image 524
IT_Philic Avatar asked Dec 09 '22 09:12

IT_Philic


2 Answers

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:

  • Have an array of size 26 (the size of the English alphabet). Now you iterate on the String and for each char in it you add 1 in the corresponding cell in the helper array.
  • Use a 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.

like image 118
Maroun Avatar answered Jan 20 '23 17:01

Maroun


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. 
like image 42
TheLostMind Avatar answered Jan 20 '23 18:01

TheLostMind