'rearrange the characters of a string so that any two adjacent characters are not the same
How to rearrange the characters of a string so that any two adjacent characters are not the same? using c# c# Without using Hashmaps and Dictionary I managed to find each element of the string, and the occurrence of each element. This is what I've done so far
Solution 1:[1]
Using LINQ, you can gather the characters of the string
, group them by duplicate characters, then pivot the groups and join then back into a string
.
First, some extension methods to make Join
easier:
public static class IEnumerableExt {
public static string Join(this IEnumerable<char> chars) => String.Concat(chars); // faster >= .Net Core 2.1
public static string Join(this IEnumerable<string> strings) => String.Concat(strings);
}
Then, an extension method to pivot an IEnumerable<IEnumerable<T>>
:
public static class IEnumerableIEnumerableExt {
public static IEnumerable<IEnumerable<T>> Pivot<T>(this IEnumerable<IEnumerable<T>> src) {
var enums = src.Select(ie => ie.GetEnumerator()).ToList();
var hasMores = Enumerable.Range(0, enums.Count).Select(n => true).ToList();
for (; ; ) {
var oneGroup = new List<T>();
var hasMore = false;
for (int j1 = 0; j1 < enums.Count; ++j1) {
if (hasMores[j1]) {
hasMores[j1] = enums[j1].MoveNext();
hasMore = hasMore || hasMores[j1];
if (hasMores[j1])
oneGroup.Add(enums[j1].Current);
}
}
if (!hasMore)
break;
yield return oneGroup;
}
for (int j1 = 0; j1 < enums.Count; ++j1)
enums[j1].Dispose();
}
}
Finally, use these to solve your problem:
var s = "How to rearrange the characters of a string";
var tryAns = s.OrderBy(c => c)
.GroupBy(ch => ch)
.Pivot()
.Select(gch => gch.Join())
.Join();
var dupRE = new Regex(@"(.)\1", RegexOptions.Compiled);
var hasDups = dupRE.IsMatch(tryAns);
// tryAns will be " Hacefghinorstw aceghnorst aeort aert ar r "
// hasDups will be false
If the resulting string has two adjacent identical characters, then hasDups
will be true.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | NetMage |