Reputation: 123
I am having difficulties for formulating a possible solution, for a question called string compression where I need to compress a string based on repeating characters
INPUT: aabbccddeeff OUTPUT a2b2c2d2e2f2
INPUT: abbbccddeeff OUTPUT: a1b3c2d2e2f2
My code currently is able to identify repeating characters(I will implement logic for non repeating characters soon)
My question is How would I input the amount of times a character appears, i am thinking of using an empty string and dynamically building up a solution however this is proving to be relatively difficult
My code
*public static void strCompression(String word){
char[] arr = word.toCharArray();
int idx = 0;
int jdx = idx + 1;
int times = 0;
String empt = "";
while (idx<arr.length)
{
while(jdx != arr.length)
{
if(arr[idx] == arr[jdx])
{
times = (jdx - idx) + 1;
}
idx = jdx;
++jdx;
}
++idx;
}
}*
Can someone give me some guidance on how i would go about doing this.
Also in my code snippet, index i gets index j if there is not duplicate elements, it then starts counting to check if there are any other duplicate elements. so for example
aaaaabbbbb
pointer is idx is at 0 which is a, jdx counts how many times a occurs, when index at i is not equal to index at j(different char values) then we will set the index at i to be equal to index at j
Should this be idx = jdx + 1 or idx = jdx;
Upvotes: 0
Views: 71
Reputation: 1700
pointer is idx is at 0 which is a, jdx counts how many times a occurs, when index at i is not equal to index at j(different char values) then we will set the index at i to be equal to index at j
Yeah, idx = jdx
is correct.
Logic:
You have implemented it until getting the frequency of an element.
So moving on to the next part,
empt
and change the indices accordingly and exit the inner while loop
.
// if element is same change the times accordingly
if(arr[idx] == arr[jdx])
{
times = (jdx - idx) + 1;
}
// if different add to empt and change idx and jdx accordingly
else {
empt += arr[idx];
empt += times.toString();
times = 1;
idx = jdx;
jdx++;
break;
}
else statement
( this happens when last element is unique (or) same is its previous elements) i.e basically to handle the last element.while (idx < len)
{
while(jdx != len)
{
...
}
if (jdx == len) {
times = (jdx - idx);
empt += arr[idx];
empt += times.toString();
break;
}
}
Full Code:
int times = 1; // if the first element appears only once
while (idx < len)
{
while(jdx != len)
{
if(arr[idx] == arr[jdx])
{
times = (jdx - idx) + 1;
}
else {
empt += arr[idx];
empt += times.toString();
times = 1; // resetting times = 1
idx = jdx;
jdx++;
break;
}
++jdx;
}
if (jdx == len) {
times = (jdx - idx);
empt += arr[idx];
empt += times.toString();
break;
}
}
Note:
There is some redundancy here, like updating the times
everytime you encounter a same element, so I leave this as an exercise.
Upvotes: 1