题目描述:给定一个字符串S
,检查是否能重新排布其中的字母,使得两相邻的字符不同。
若可行,输出任意可行的结果。若不可行,返回空字符串。
示例 1:
输入: S = "aab"
输出: "aba"
示例 2:
输入: S = "aaab"
输出: ""
注意:
S 只包含小写字母并且长度在[1, 500]区间内。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reorganize-string
解题思路:1.取得每个字符的个数;
2.根据个数进行升序排列;
3.依次将相同字符间隔插入到新的String Builder中。
C# 代码如下:
static string reorganizeString(string S)
{
int len = S.Length;
if (len <= 1) return S;
int max = 1;//字符出现的次数的最大值
Dictionary<char, int> dic = new Dictionary<char, int>(len);//保存每个字符出现的次数
for (int i = 0; i < len; i++)
{
char c = S[i];
if (dic.ContainsKey(c))
{
dic[c]++;
max = Math.Max(dic[c], max);
}
else dic.Add(c, 1);
}
if (len % 2 == 0)
if (max > (len / 2)) return "";//偶数个字符,某个字符的个数大于一半,就不过符合规则
if (max > (len / 2 + 1)) return "";//奇数个字符,某个字符的个数大于len / 2 + 1,就不过符合规则
var dicSort = from objDic in dic orderby objDic.Value select objDic;//进行升序排列
StringBuilder sb = new StringBuilder(len);
foreach (var item in dicSort)
{
if (sb.Length == 0)
sb.Append(item.Key, item.Value);//第一个字符直接append
else
for (int j = 0; j < item.Value; j++)
if (j * 2 > sb.Length) sb.Append(item.Key);//其他字符,从0,间隔1 开始插入。如果j * 2 > sb.Length,需要append
else sb.Insert(j * 2, item.Key);//其他字符,从0,间隔1 开始插入。
}
return sb.ToString();
}