4

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;
 }
}
Rahul
45.2k11 gold badges89 silver badges108 bronze badges
asked Feb 13, 2014 at 8:39
2
  • As Sotirios mentioned, learning debugger for this kind of tasks is very helpful. Simply put breakpoint at the beginning of your method and check step by step what's happening with a result. Commented Feb 13, 2014 at 8:44
  • I am a beginner in java.I am expected to not use functions.I have to do this only with the help of loop.Please help. Commented Feb 13, 2014 at 8:46

7 Answers 7

5

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.

answered Feb 13, 2014 at 8:44
1
  • 1
    I was going to suggest a more OOP approach to it. Have a Letter class with the value, and the frequency. That provides some direct mapping and might make cleaner code. Only commenting to give OP another angle. Commented Feb 13, 2014 at 8:46
5
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. 
answered Feb 13, 2014 at 8:49
2
  • Since i m a beginner in java.I dont know about Hashmap and its use?Any easier solution would help. Commented Feb 13, 2014 at 8:52
  • @user3305143 - This is perhaps easier than your approach... :).. 5 to 6 lines of code will do it.. Commented Feb 13, 2014 at 9:05
2

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;
}
answered Feb 13, 2014 at 8:57
4
  • Thank you so much for your help.I found my error @kai Commented Feb 13, 2014 at 9:01
  • your code is returning the most occuring character in a string but i have to find the longest sequence of chars.For example if the string is "Pressure" then the output will be "ss" but it is giving the output "rr". Commented Feb 13, 2014 at 9:14
  • now it works, but that was such little mistake that you can found it out by yourself. you only have to change continue to break. Commented Feb 13, 2014 at 9:34
  • but your code have the same behaviour. it counts the occurence too, because you didnt break the loop it is like if(ch==ch1)result+ch; and thats typicall for counting the occurence. Commented Feb 13, 2014 at 9:37
2

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;
}
answered Feb 13, 2014 at 8:58
2
  • Thank you so much for helping me with this problem @ashot Commented Feb 13, 2014 at 9:17
  • @user3305143, BTW more effective "patch":) remove i++ from for loop and after if{}(outside of if) add i = j; Commented Feb 13, 2014 at 9:39
1

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.

answered Jun 20, 2017 at 12:58
0

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.

Jason Braucht
2,36819 silver badges32 bronze badges
answered Mar 24, 2017 at 15:20
0

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
answered Jun 28, 2024 at 2:04

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.