惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
IT之家
IT之家
Hugging Face - Blog
Hugging Face - Blog
J
Java Code Geeks
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 叶小钗
MyScale Blog
MyScale Blog
G
Google Developers Blog
Microsoft Azure Blog
Microsoft Azure Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
Google DeepMind News
Google DeepMind News
Engineering at Meta
Engineering at Meta
The Cloudflare Blog
Martin Fowler
Martin Fowler
酷 壳 – CoolShell
酷 壳 – CoolShell
N
Netflix TechBlog - Medium
MongoDB | Blog
MongoDB | Blog
I
InfoQ
WordPress大学
WordPress大学
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security

博客园 - Na57

ASP.NET MVC应用中一个诡异错误的处理 使用Enterprise Library 4.0 Logging 的问题 8. Action过滤 6. 视图和生成助手 5. 控制器和Action方法 2. 创建基本的MVC项目 3. URL路由 - Na57 - 博客园 4. 用MVC实现URL路由 Google笔记本迈向烂笔头 XML and Databases 笔记 烂笔头又来了 - Na57 - 博客园 GeoServer抛异常IllegalArgumentException的原因 CSS学习 关于CSS中float属性的理解 ItemCreated与ItemDataBound 《SAML简介:安全地共享数字身份信息》读后感 JavaScript 学习(2) - JS的内建对象 JavaScript from C#(入门篇) 2006.6《程序员》笔记
<程序员>200711期算法擂台的解答
Na57 · 2007-11-27 · via 博客园 - Na57

这期的题目是<完美的代码>,具体题目请看杂志.
解答程序如下:

 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 

这是我的想法,欢迎赐教.