487, Reconstruct string

Insert picture description here

If you want to see more algorithm questions, you can scan the QR code above to follow my WeChat official account " Data Structure and Algorithms ". Up to now, I have updated more than 500 algorithm questions in the official account , some of which have been sorted into pdf documents. , As of now, there are more than 800 pages in total (and will continue to increase), you can reply to the keyword "pdf" in the official account to download.


Problem Description

Given a string S, check whether the letters can be rearranged so that two adjacent characters are different.

If feasible, output any feasible results. If it is not feasible, return an empty string.

Example 1:

Input : S = "aab"

Output : "aba"

Example 2:

Input : S = "aaab"

Output : ""

note:

  • S contains only lowercase letters and the length is in the interval [1, 500].

problem analysis

This question is to rearrange the characters in the string S so that any two adjacent characters are different. If it can be done, it will return the arranged string, if it can’t, it will return an empty string.


If you want to make two adjacent characters different, then the number of the number with the most occurrences must meet the following conditions, as shown in the figure below, for example, the following a is the most frequent occurrence

image

At this time the number of a has reached the critical value, if there is one more a, then at least two a are adjacent. So the critical value of the number of characters that appears the most here is threshold = (length + 1) >> 1 (where length is the length of the string)


If the two adjacent characters can be made different, we can first put the character with the most occurrences in the position where the subscript of the new array is an even number, that is, start from the first position of the array, and use other characters after finishing. Fill the remaining subscripts of the array with even numbers. If the subscripts are even filled, we start with the subscript 1, which is the second position of the array, and fill the subscripts with odd numbers. s position.


Note that it is possible to put the character with the most occurrences in the position where the string subscript is an odd number first. For example, the example we gave above, abacaba, could have been satisfied. If it is placed in the position where the subscript is an odd number, the last a cannot be placed. Unless it is placed at the top, it will become the subscript as an even number. Location.

image

code show as below

public String reorganizeString(String S) {
    
    
    //把字符串S转化为字符数组
    char[] alphabetArr = S.toCharArray();
    //记录每个字符出现的次数
    int[] alphabetCount = new int[26];
    //字符串的长度
    int length = S.length();
    int max = 0, alphabet = 0, threshold = (length + 1) >> 1;
    //找出出现次数最多的那个字符
    for (int i = 0; i < length; i++) {
    
    
        alphabetCount[alphabetArr[i] - 'a']++;
        if (alphabetCount[alphabetArr[i] - 'a'] > max) {
    
    
            max = alphabetCount[alphabetArr[i] - 'a'];
            alphabet = alphabetArr[i] - 'a';
            //如果出现次数最多的那个字符的数量大于阈值,
            // 说明他不能使得两相邻的字符不同,
            // 直接返回空字符串即可
            if (max > threshold)
                return "";
        }
    }
    //到这一步说明他可以使得两相邻的字符不同,
    // 我们随便返回一个结果,res就是返回
    //结果的数组形式,最后会再转化为字符串的
    char[] res = new char[length];
    int index = 0;
    //先把出现次数最多的字符存储在数组下标为偶数的位置上
    while (alphabetCount[alphabet]-- > 0) {
    
    
        res[index] = (char) (alphabet + 'a');
        index += 2;
    }
    //然后再把剩下的字符存储在其他位置上
    for (int i = 0; i < alphabetCount.length; i++) {
    
    
        while (alphabetCount[i]-- > 0) {
    
    
            //如果偶数位置填完了,我们就让index从1开始,
            // 填充下标为奇数的位置
            if (index >= res.length) {
    
    
                index = 1;
            }
            res[index] = (char) (i + 'a');
            index += 2;
        }
    }
    return new String(res);
}

to sum up

The direct judgment of this question is relatively simple, we only need to count the characters with the most occurrences. But this question also needs to return the result, so the easiest way is to start the character with the most occurrences from the first position of the array, and put every other character . After putting it, put other characters from the back, also every other one. If it exceeds the array, start putting it from the second position of the array, also every other one, so as to ensure that the result will not be wrong, and also A lot less judgment.

Guess you like

Origin blog.csdn.net/abcdef314159/article/details/112208122