Summary of work---find out repeated character groups, and add the serial number in this group to each group of characters

1 Introduction

A recent requirement, personal understanding can be sorted into an algorithm problem. 

The original requirement is to find the ledger of a certain process from the database, and arrange it in ascending order according to the date of completion. Depending on the settlement date, the corresponding number will be generated according to the rules. For example, the database has a total of 30 pieces of data, 10 pieces of data on May 13, 2021, 10 pieces of data on June 18, 2021, 10 pieces of data on September 7, 2021, and 10 pieces of data on May 13, 2021 based on time, minutes and seconds The sequence number is 2021-0513-1 to 2021-0513-10, and the 10 data on June 18, 2021 are numbered 2021-0618-1 to 2021-0618-10 according to the sequence of hours, minutes and seconds, and September 2021. The 10 pieces of data on the 7th are numbered from 2021-0907-1 to 2021-0907-10 according to the order of hours, minutes and seconds.

2 Abstract Requirements

According to the original requirements, it can be abstracted into a given string in ascending order of ASCII code, find the same characters in the string and group them, and give the order of each character in the same group of characters, starting from 1.

For example: input: a,

           output: a1;

           Input: aaa,

           output: a1a2a3;

           Input: accdd,

           Output: a1c1c2d1d2.

3 code implementation

public class RepeatChar {

    public static void main(String[] args) {

        List<String> input = new ArrayList<>(16);
        input.add("");
        input.add("a");
        input.add("qwe");
        input.add("aabbcdddfffffff");
        input.add("jyhgggue");
        input.add("aaaaaaaa");
        for (String s: input) {
            System.out.println(repeatChar(s));
        }
    }


    public static String repeatChar(String s){
        int len = s.length();
        if (len == 0){
            return "";
        }
        int index = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < len; i++){
            //后一个字符与前一个字符不相同
            if (s.charAt(i - 1) != s.charAt(i)){
                for (int j = 0; j < i - index; j++) {
                    sb.append(s.charAt(index + j)).append(j + 1);
                }
                index = i;
            }
        }
        //最后一组字符需要单独添加
        for (int i = 0; i < len - index; i++) {
            sb.append(s.charAt(index + i)).append(i + 1);
        }
        return sb.toString();
    }
}

4 output result

5 Code Analysis 

In the first for loop, since the comparison could not find the last set of characters, a second for loop was added to number the last set of characters. The time complexity of the code is o( n^{2}).

Guess you like

Origin blog.csdn.net/honor_zhang/article/details/120720666