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;
}
}
-
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.Piotr Chojnacki– Piotr Chojnacki2014年02月13日 08:44:20 +00:00Commented 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.IT_Philic– IT_Philic2014年02月13日 08:46:31 +00:00Commented Feb 13, 2014 at 8:46
7 Answers 7
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 thechar
as a key and the number it appears as the value. If it's a newchar
you simply put it with 0 value, if it exists, you increment the existing value.
Tip: Use a debugger, it can save your life.
-
1I 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.christopher– christopher2014年02月13日 08:46:17 +00:00Commented Feb 13, 2014 at 8:46
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.
-
Since i m a beginner in java.I dont know about Hashmap and its use?Any easier solution would help.IT_Philic– IT_Philic2014年02月13日 08:52:13 +00:00Commented Feb 13, 2014 at 8:52
-
@user3305143 - This is perhaps easier than your approach... :).. 5 to 6 lines of code will do it..TheLostMind– TheLostMind2014年02月13日 09:05:45 +00:00Commented Feb 13, 2014 at 9:05
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;
}
-
Thank you so much for your help.I found my error @kaiIT_Philic– IT_Philic2014年02月13日 09:01:31 +00:00Commented 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".IT_Philic– IT_Philic2014年02月13日 09:14:51 +00:00Commented 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.kai– kai2014年02月13日 09:34:22 +00:00Commented 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.kai– kai2014年02月13日 09:37:34 +00:00Commented Feb 13, 2014 at 9:37
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;
}
-
Thank you so much for helping me with this problem @ashotIT_Philic– IT_Philic2014年02月13日 09:17:10 +00:00Commented Feb 13, 2014 at 9:17
-
@user3305143, BTW more effective "patch":) remove
i++
from for loop and afterif{}
(outside of if) addi = j
;Ashot Karakhanyan– Ashot Karakhanyan2014年02月13日 09:39:12 +00:00Commented Feb 13, 2014 at 9:39
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.
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.
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