[LeetCode one question per day] [Medium]767. Refactoring string

[LeetCode one question per day] [Medium]767. Refactoring string

767. Refactoring strings

767. Refactoring strings

Algorithm idea: string

topic:

Insert picture description here

Problem solution
ideas:

  1. First, put the letter with the largest number of repetitions in an even position (0,2,4,,,). If it cannot be put down, there must be repeated letters adjacent to each other. If it is possible, there must be such a string;
  2. Then put the remaining letters in the remaining even-numbered positions (if any), and then put the odd-numbered positions (1,3,5,7,,,,); this ensures that each letter placed is the same as the previous one, Separate (meet non-adjacent requirements)

java code

class Solution {
    
    
    public String reorganizeString(String S) {
    
    
		int[] m = new int[26];
		int max = 0;//字重复最大频率
		int alpha = 0;//最大重复字母下标
		int maxEdge = (S.length() + 1) / 2;//字母重复最大频率上限
		for (char ch : S.toCharArray()) {
    
    
			int i = ch-'a';
			m[i]++;//统计次数
			if (m[i] > max) {
    
    
				max = m[i];
				alpha = i;
				if (max > maxEdge) {
    
    //如果最大的不能放下,则不可能存在这样的字符串
					return "";
				}
			}
		}
		
		int n = S.length();
		char[] res = new char[n];
		int index = 0;
		while (m[alpha] > 0) {
    
    //将最大的重复字母放入偶数格子
			res[index] = (char)(alpha + 'a');
			m[alpha]--;
			index += 2;//放入偶数格子
		}
        //把剩下的字符存储在其他位置上(先放剩下偶数格子,然后放奇数格子)
        for (int i = 0; i < 26; i++) {
    
    
            while (m[i] > 0) {
    
    
                if (index >= n) {
    
    
                    index = 1;//如果越界后,表示偶数格子已经放完了,从奇数格子开始存放
                }
                res[index] = (char) (i + 'a');
                m[i]--;
                index += 2;
            }
        }
        return new String(res);
    }
}

Guess you like

Origin blog.csdn.net/qq_39457586/article/details/110391010