IT_Philic
IT_Philic

Reputation: 321

How to return longest sequence of chars in a string in 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;
    }
}

Upvotes: 4

Views: 12352

Answers (7)

Victor Eke
Victor Eke

Reputation: 465

I know this question was asked 10 years ago but here's a complete step on how I would implement it using @lostming's guide:

public class mostCommonChar {
    /**
     * @throws IllegalArgumentException Character length must be at least 2
     * @return String
     * @param word A string of characters
     * @apiNote Returns the longest sequence of character in a given word or text
     * */

    public static String getMostCommonChar(String word) {
        int occurrence = 0;
        String mostCommonChar = "";
        String[] characters = {};
        HashMap<String, Integer> characterList = new HashMap<String, Integer>();

        if(word.length() < 2) {
            throw new IllegalArgumentException();
        }

        characters = word.trim().split("");
        for(String character : characters) {
            if(characterList.containsKey(character)) {
                occurrence++;
                mostCommonChar = character;
            } else {
                characterList.put(character, 1);
            }
        }
        return occurrence == 0 ? "None" : mostCommonChar;
    }
}

// input = hellloo, output = l
// input = abcd, output = None
// input = x, output = IllegalArgumentException

Upvotes: 0

Phoenix
Phoenix

Reputation: 31

This can be solved easily using HashMap. Checkout this sample code:

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class MaximumOccuringCharUsingHashMap {
  public static void main(String[] args) {
  String test = "test samples";
  MaximumOccuringCharUsingHashMap mc = 
      new MaximumOccuringCharUsingHashMap();
  System.out.println( mc.findMaximunOccurenceCharacter(test));
}
  char findMaximunOccurenceCharacter(String input){
      Map<Character, Integer> countHash = 
          new HashMap<Character, Integer>();
      for(int i=0; i<input.length() ;i++ ){
          char currentChar = input.charAt(i);
          if(countHash.get(currentChar)==null){
              countHash.put(currentChar, 1);
          }else{
              countHash.
              put(currentChar, countHash.get(currentChar)+1);
          }
      }

      int max = Collections.max(countHash.values());

      char maxCharacter =0;
      for(Entry<Character, Integer> entry :countHash.entrySet()){
          if(entry.getValue() == max){
              maxCharacter = entry.getKey();
          }
      }
      return maxCharacter;
  }
}

Above code will print s as output, which is occurring maximum number of times in the given String.

Upvotes: 1

user7763030
user7763030

Reputation: 1

Try This...

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println(maxLen(null));
        System.out.println(maxLen(""));
        System.out.println(maxLen("a"));
        System.out.println(maxLen("aa"));
        System.out.println(maxLen("abcddd"));
        System.out.println(maxLen("abcd"));
        System.out.println(maxLen("aabbba"));
    }

    public static String maxLen(String input) {
        // Avoid NPEs
        if (input == null) {
            return null;
        }
        int maxLen = 0;
        int tempLen = 0;
        char prevChar = 0;
        char c = 0;
        char repeatChar = 0;
        for (int i = 0; i < input.length(); i++) {
            c = input.charAt(i);
            if (c == prevChar) {
                tempLen++;
                if (tempLen > maxLen)
                    repeatChar = c;
            } else {
                maxLen = (tempLen > maxLen) ? tempLen : maxLen;
                prevChar = c;
                tempLen = 1;
            }
        }
        maxLen = (tempLen > maxLen) ? tempLen : maxLen;
        if (maxLen == 0 || maxLen == 1)
            return "no sequence found";
        else {
            String str = "";
            for (int i = 1; i <= maxLen; i++)
                str += String.valueOf(repeatChar);
            return str;
        }
    }
}

This will pass all test cases.

Upvotes: 0

kai
kai

Reputation: 6887

If there are three 'l' you only add two and in the next step are two 'l' and you add one of them. Then the same with the two 'o' where you are adding one. You only have to clear the result string when you step to the next letter and before save the result in another variable, but only if its is longer!

public String longestSequenceOfChar(String str){
    String interimresult="";
    String result="";              //final result
    for(int i=0;i<str.length();i++){
        char ch=str.charAt(i);
        interimresult += ch;       //add the letter once
        for(int j=i+1;j<str.length();j++){
            char ch1=str.charAt(j);
            if(ch!=ch1){
                break;
            }
            interimresult +=ch;
        }
        if(interimresult.length()>result.length())//store the result if it is longer 
            result = interimresult;
        interimresult = "";                   //clear to continue with the next letter
    }
    return result;
}

Upvotes: 2

Ashot Karakhanyan
Ashot Karakhanyan

Reputation: 2830

Here is a solution:

public String longestSequenceOfChar(String str) {
    String result = "";

    for (int i = 0; i < str.length(); i++) {
        int j = i;
        while(j < str.length() && str.charAt(j) == str.charAt(i)) {
            j++;
        }

        // If this one is longer than previous, then asign it to result.
        if(j - i > result.length()) {
            result = str.substring(i, j);
        }
    }
    return result;
}

Upvotes: 2

TheLostMind
TheLostMind

Reputation: 36304

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. 

Upvotes: 5

Maroun
Maroun

Reputation: 95948

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.

Upvotes: 5

Related Questions