我最终创建了下面的扩展方法,它工作得非常出色。感谢乔吹他出色和有效的建议:
public static string Contract(this string e, int maxLength)
{
if(e == null) return e;
int questionMarkIndex = e.IndexOf('?');
if (questionMarkIndex == -1)
questionMarkIndex = e.Length - 1;
int lastPeriodIndex = e.LastIndexOf('.', questionMarkIndex, 0);
string question = e.Substring(lastPeriodIndex != -1 ? lastPeriodIndex : 0, questionMarkIndex + 1).Trim();
var punctuation =
new [] {",", ".", "!", ";", ":", "/", "...", "...,", "-,", "(", ")", "{", "}", "[", "]","'","\""};
question = punctuation.Aggregate(question, (current, t) => current.Replace(t, ""));
IDictionary<string, bool> words = question.Split(' ').ToDictionary(x => x, x => false);
string mash = string.Empty;
while (words.Any(x => !x.Value) && mash.Length < maxLength)
{
int maxWordLength = words.Where(x => !x.Value).Max(x => x.Key.Length);
var pair = words.Where(x => !x.Value).Last(x => x.Key.Length == maxWordLength);
words.Remove(pair);
words.Add(new KeyValuePair<string, bool>(pair.Key, true));
mash = string.Join("", words.Where(x => x.Value)
.Select(x => x.Key.Capitalize())
.ToArray()
);
}
return mash;
}
此合约下到15个字符:
- 这没有任何prereqs - 写一篇文章...:PrereqsWriteEssay
- 您选择了一辆车:YouveSelectedCar
这是一个很大的问题,暴露了使用启发式算法和重型AI的许多问题。很好的问题。 – Fattie 2010-11-06 13:51:28