Reputation:
folks! I've been practicing different tasks on Java and this one has been taking me a while to figure out. A user has to enter only String
of letters and for example, if a user enters smth like wwwzddfffff
the ouput should be 3w1z2d5f
or, another example, kklllk
and the ouput should be 3k3l
. The method runLength()
takes the occurrence of each repeating character and outputs that number along with a single character of the repeating sequence.
What I am getting is:
Enter any String:
wwwwzzzz
7z
import java.util.Scanner;
public class RunLength {
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
System.out.println("Enter any String: ");
String word = kbd.nextLine();
String result = runLength(word);
System.out.println(result);
}
public static String runLength(String word)
{
char[] chars = word.toCharArray();
char firstChar = chars[0];
char temp = 0;
int count = 0;
String result = "";
for(int i = 1; i < chars.length; i++)
{
if(firstChar == chars[i])
{
temp = firstChar;
count++;
result = count+""+temp;
}
else if(firstChar != chars[i])
{
temp = chars[i];
count++;
result = count+""+temp;
}
}
return result;
}
}
Upvotes: 2
Views: 640
Reputation: 3898
class test
{
public static void main(String args[])
{
System.out.println(runlength("aaabbc"));
}
static String runlength(String s)
{
String current="";
int count = 1;
char[] c = s.toCharArray();
for(int i = 1; i < c.length; i++)
{
if (c[i]==c[i-1])
count++;
else
{
current = current + count + Character.toString(c[i-1]);
count = 1;
}
}
return current + count + Character.toString(c[c.length-1]);
}
}
Upvotes: 1
Reputation: 2922
Would like you to rewrite runLength method.
public static Map runLength(String word) {
char[] chars = word.toCharArray();
char firstChar = chars[0];
Map charMap = new HashMap();
for(int i = 0; i < chars.length; i++) {
if(charMap.contains(chars[i])
charMap.put(chars[i],++charMap.get(chars[i]));
else
charMap.put(chars[i],1);
}
return charMap;
}
// in the main method
Map myMap = runLength(word);
for (Entry entry : myMap.entrySet()) {
System.out.print(myMap.get(entry.getKey())+entry.getKey());
}
Upvotes: 0
Reputation: 8756
Sounds like a HashMap will solve your problem. Try:
Map<Character, Integer> counter = new HashMap<Character, Integer>();
char[] chars = word.toCharArray();
for(char c: chars){
if(counter.containsKey(c)){
counter.put(c, c.get(c) ++);
}
else{
counter.put(c, 1);
}
}
Then to print:
StringBuilder builder = new StringBuilder();
for (Character c : counter.keySet()) {
builder.append(c);
builder.append(counter.get(c));
}
return builder.toString();
Upvotes: 0