<程序员>200711期算法擂台的解答

这期的题目是<完美的代码>,具体题目请看杂志.
解答程序如下:
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using System.IO;
 5 
 6 namespace Huiwen
 7 {
 8     class Program
 9     {
10         // 第一个参数是输入的文件的名称.
11         static void Main(string[] args)
12         {
13             // 从文件读取数据
14             StreamReader sr = File.OpenText(args[0]);
15             int length = Convert.ToInt32(sr.ReadLine());
16             char[] cs = sr.ReadLine().ToCharArray();
17 
18 
19             int count = 0;
20             
21             // 通过循环做置换
22             for (int i = 0; i < length/2; i++)
23             {
24                 char c = cs[i];
25                 
26                 // 从末尾找第一个与c相同的字符的位置.
27                 int index = LastIndex(cs, c, i+1, length - i - 1);
28 
29                 // 若未找到,则证明该字符串不能变为回文串.
30                 if (index == -1)
31                 {
32                     Console.WriteLine("Impossible");
33                     return;
34                 }
35 
36                 // 记录需要置换的次数.
37                 count += (length - 1 - i - index);
38 
39                 // 交换两个字符.
40                 cs[index] = cs[length - 1 - i];
41                 cs[length-1-i] = c;
42             }
43 
44             Console.WriteLine(count);
45         }
46 
47         // 从字符串数组中取字符串的位置索引.未找到则返回-1.
48         static int LastIndex(char[] ca, char c, int startIndex, int endIndex)
49         {
50             for (int i = endIndex; i >= startIndex; i--)
51             {
52                 if (ca[i].Equals(c)) return i;
53             }
54             return -1;
55         }
56     }
57 }
58 

这是我的想法,欢迎赐教.
posted on 2007-11-27 16:26  Na57  阅读(442)  评论(1编辑  收藏  举报