我必须编写一个程序,该程序将用户输入的字符串中的字母进行洗牌,以便不包含两个相同的相邻字母。如果这是不可能的,程序应该返回出现次数最多的字母。(不使用LinQ).
For the input: tttesst
输出应该是:
tetstst
为输入:aaaabc
输出应为:a
using System;
string example = "tttesst";
var orderList = SortArray(example.ToCharArray());
string lettersString = string.Empty;
for (int i = 0; i < orderList.Length; i++)
{
lettersString += orderList[i];
if (i + 1 == orderList.Length)
{
break;
}
if (orderList[i] != orderList[i + 1])
{
lettersString += " ";
}
}
Console.WriteLine(lettersString);
Console.ReadLine();
static char[] SortArray(char[] array)
{
int length = array.Length;
for (int i = 0; i < length; i++)
{
for (int j = i + 1; j < length; j++)
{
if (array[i] > array[j])
{
char temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array;
}
这是我所尝试的,但输出是:e ss tttt
。如何将这些相同字母的子字符串组合成一个没有相邻字母的字符串?
这就是您如何获得总是区域字符串而没有相邻字符的方法。
using System;
using System.Linq;
namespace ShuffleString
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Shuffle("aaaaabc"));
}
static string Shuffle(string input)
{
// Convert the input string to a char array
char[] inputArray = input.ToCharArray();
// Shuffle the char array
Random rng = new Random();
int n = inputArray.Length;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
char value = inputArray[k];
inputArray[k] = inputArray[n];
inputArray[n] = value;
}
// Rebuild the string, skipping any characters that are the same as the previous character
string shuffledString = "";
char previousChar = ' '; // use a null char as the initial value for previousChar
foreach (char c in inputArray)
{
if (c != previousChar)
{
shuffledString += c;
previousChar = c;
}
}
return shuffledString;
}
}
}