通過輸入段和輸出是清楚嘗試字謎檢查器,但內存限制超過該我試圖減少內存使用在下面字謎程序 - C#
using System;
class Program
{
static void Main(string[] args)
{
string[] arr = (Punct(Console.ReadLine()).ToLower()).Split(' ');
string a = string.Empty;
System.Collections.Generic.Dictionary<string, string> dn = new System.Collections.Generic.Dictionary<string, string>(); // *2
foreach (string s in arr)
{
string st = sort(s);
if (dn.ContainsKey(st))
{
if (dn[st] != s)
{
if (a.Contains(dn[st]))
a = a.Replace(dn[st], dn[st] + " " + s); // *1
else
a = a + dn[st] + " " + s + "\n";
dn[st] = s;
}
}
else
dn.Add(st, s);
}
Console.Write(a);
}
public static string sort(string s)
{
char[] chars = s.ToCharArray();
Array.Sort(chars);
return new string(chars);
}
public static string Punct(string s)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (char c in s)
{
if (!char.IsPunctuation(c))
sb.Append(c);
}
return sb.ToString();
}
}
在指定
此代碼檢查與分析器,字符串函數需要大量的內存和其他字典,所以,我的問題是我如何優化上述代碼到最少的內存,或者我使用的任何代碼或聲明是不必要的?
輸入:
世界部分地區夏季有將近24個小時的陽光。丹在他的頭上戴了一根皮帶,以表明自己是領導者,他想知道在他前面躺着什麼樣的陷阱。
輸出:
部分帶陷阱
丹和
在你的主循環使用'StringBuilder' ..你變化無常的字符串變量所有的時間與不同的結果。這導致很多創建的字符串數據。使用'StringBuilder'來停止這個。 –