麻烦各位大大帮我解决字符串连接问题,谢谢了
算法实验题1.3字符串连接问题★问题描述
所谓字符串连接问题是指将n个字符串前后拼接成一个字符串。不同的接力方式将得到不同的结果。例如n =3时,3个字符串ab,aa,cd 相互连接可能的结果有:aaabcd,aacdab,abaacd,abcdaa,cdaaab,cdabaa。
★编程任务
对于给定的n个字符串,请找出一种最佳的连接方式,使得采用该连接方式得到的字符串在所有连接的结果中,字典序最小。
★数据输入
第一行是一个正整数n(1 <=n<=5000),接下来n行每行一个需要连接的字符串。字符串仅由大小写字母组成,其长度的范围是[1..100]。
★数据输出
输出一行连接n个子串所得到的字典序最小字符串。
输入文件示例
3
ab
aa
cd
输出文件示例
aaabcd --------------------编程问答--------------------
int n = Convert.ToInt32(Console.ReadLine());--------------------编程问答-------------------- 作业题。。。 --------------------编程问答-------------------- --------------------编程问答-------------------- 是作业题,感谢 caozhy 的热情回复!!! --------------------编程问答--------------------
List<string> list = new List<string>();
for (int i = 0; i < n; i++)
list.Add(Console.ReadLine());
string output = "";
list.OrderBy(x => x).Select(x => x).ToList()
.ForEach(x => output += x);
Console.WriteLine(output);
--------------------编程问答-------------------- 哦,ls几位的程序是有问题的,试试bb和bba --------------------编程问答-------------------- 不过这题并不麻烦,只要重载一些Sort的比较部分就可以了 --------------------编程问答--------------------
练了一下手,哈哈
int n = Convert.ToInt32(Console.ReadLine());
List<string> list = new List<string>();
while (n-- != 0) list.Add(Console.ReadLine());
list.Sort();
list.ForEach(x => Console.Write(x));
--------------------编程问答-------------------- 简单弄的话,这样应该就可以
看了一下,的确有问题,写了个方法,现在算是好了,不知还有其他问题不。。。呵呵!
static void Test()
{
while (true)
{
int n = Convert.ToInt32(Console.ReadLine());
List<string> list = new List<string>();
while (n-- != 0) list.Add(Console.ReadLine());
list.Sort(Comp);
list.ForEach(x => Console.Write(x));
Console.ReadKey();
}
}
static int Comp(string left, string right)
{
int il = 0, ir = 0;
while (il < left.Length && ir < right.Length)
{
if (left[il] != right[ir])
{
return left[il] - right[ir]>= 0 ? 1 : -1;
}
++il; ++ir;
}
while (il != left.Length)
{
if (left[il] != left[0])
return left[0] - left[il] >= 0 ? 1 : -1;
++il;
}
while (ir != right.Length)
{
if (right[ir] != right[0])
return right[0] - right[ir] >= 0 ? 1 : -1;
++ir;
}
return 0;
}
static int Comp(string left, string right)
{
return string.CompareOrdinal(left + right, right + left);
}
补充:.NET技术 , C#