[LeetCode-767][重构字符串][reorganize-string]
原题
链接:https://leetcode-cn.com/problems/reorganize-string
【中文】
给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。
若可行,输出任意可行的结果。若不可行,返回空字符串。
示例 1:
输入: S = "aab"
输出: "aba"
示例 2:
输入: S = "aaab"
输出: ""
注意:
S 只包含小写字母并且长度在[1, 500]区间内。
【英文】
Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
If possible, output any possible result. If not possible, return the empty string.
Example 1:
Input: S = "aab"
Output: "aba"
Example 2:
Input: S = "aaab"
Output: ""
Note:
S will consist of lowercase letters and have length in range [1, 500].
题解思路:
统计各各个字母出现的频次,并标记出现次数最多的字母。若该字母出现的频次maxNum和给定字符串长度len不满足len >= 2 * maxNum - 1,则无解。
满足时,先将出现频次的最高的字母每隔一个位置进行填充,然后将其余字母同样处理,每隔一个位置进行填充。这样即可保证相邻位置字母不同。
代码:
1 //method to fill alpha from position *start 2 void update(char *result, int len, char alpha, int* mark , int *start) { 3 int j = *start; 4 while (mark[alpha] != 0) { 5 if (j > len - 1) 6 j = 0; 7 // find first not filled position from start position given 8 if(result[j] != 0) { 9 j++; 10 continue; 11 } 12 result[j] = alpha; 13 mark[alpha]--; 14 j = j + 2; 15 } 16 } 17 18 // only for debug using 19 void outputResult(char *result, int len) { 20 int i; 21 printf("result:\n"); 22 for (i= 0; i < len; i++) { 23 printf("[%c]", result[i]); 24 } 25 printf("\n"); 26 } 27 28 char * reorganizeString(char * S){ 29 int mark[256] = {0}; 30 int i; 31 int len = strlen(S); 32 int maxNum = 0; 33 char maxAlpha; 34 int j; 35 int start; 36 for (i = 0; i < len; i++) { 37 mark[S[i]]++; 38 if (mark[S[i]] > maxNum) { 39 maxNum = mark[S[i]]; 40 maxAlpha = S[i]; 41 } 42 } 43 printf("done mark init\n"); 44 if (len < 2 * maxNum - 1) 45 return ""; 46 char *result = (char *)malloc(sizeof(char)*len+1); 47 memset(result, '\0' ,sizeof(char)*len+1); 48 printf("done result init\n"); 49 for (i = 0; i < maxNum; i++) 50 { 51 result[i * 2] = maxAlpha; 52 mark[maxAlpha] --; 53 start = 2 * (i + 1); 54 } 55 printf("done maxAlpha:[%c] resort\n", maxAlpha); 56 outputResult(result, len); 57 for (i = 0; i < 256; i++) { 58 while(mark[i] != 0) { 59 printf("start %c resort\n", (char)i); 60 update(result, len,(char)i, mark, &start); 61 printf("done %c resort\n", (char)i); 62 outputResult(result, len); 63 } 64 } 65 outputResult(result, len); 66 return result; 67 }

浙公网安备 33010602011771号