开发者

Create int[] (Special Counter) depending on String[]

First of all, I'm sorry about my English and I hope, at least, you can understand my problem

The user can enter different letters(for example), at most 6 letters and he can repeat i开发者_开发知识库t Let say he entered: A B C C A B B A A C C C C Of course I can put it in an array and arrange it using Arrays.sort() and it will be like

myArray = {A, A, A, A, B, B, B , C, C ,C, C, C ,C ,C}

Now, my question is: Is there a method or an algorithm to create a counter array that counts ASC till the letter been changed then counts again from 1 till the next change

My desired array would be like

myCounter = {1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 4, 5, 6}

Thank you in advance :)

PS: I know the length of the input array


Assuming arr is your input array and result is your output array, something like this should work fine:

int counter = 1;
for(int i=0 ; i<arr.length ; i++) {
    if(i>0 && arr[i-1]!=arr[i]) {
        counter = 1;
    }
    result[i] = counter;
    counter++;
}


This might do what you want (I haven't tested it):

int[] countArray = new int[arrayLength];
char lastChar = '\0';
int lastCount;
for (i = 0; i < arrayLength; i++) {
    if (chars[i] != lastChar) {
        lastCount = 0;
    }
    countArray[i] = ++lastCount;
    lastChar = chars[i];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜