我需要幫助找出一個邏輯:換上別的東西重複字符的字符串
所以,讓我們說我有一個字符串,每當有一個字符重複說string
裏面,我需要更換與(Char
+ sequence of number
)。
例如:
原始字符串:"abcdefgabfabc"
預期輸出:"abcdefga2b2f2a3b3c2"
'A' 出現3次,因此,第一 'A' 保持爲 'A',但是第二個'a'變成'a2',並且第三'a'變成'a3'並且同樣去其他字符如b,b2,b3 ...
我需要幫助找出一個邏輯:換上別的東西重複字符的字符串
所以,讓我們說我有一個字符串,每當有一個字符重複說string
裏面,我需要更換與(Char
+ sequence of number
)。
例如:
原始字符串:"abcdefgabfabc"
預期輸出:"abcdefga2b2f2a3b3c2"
'A' 出現3次,因此,第一 'A' 保持爲 'A',但是第二個'a'變成'a2',並且第三'a'變成'a3'並且同樣去其他字符如b,b2,b3 ...
var str = "abcdefgabfabc";
var chars = str.Select((c, index) =>
{
int count = str.Substring(0, index).Count(x => c == x);
if (count > 0) return c.ToString() + (count+1);
else return c.ToString();
}).SelectMany(c => c).ToArray();
var result = new string(chars); // abcdefga2b2f2a3b3c2
這對長字符串不會有效,但仍然非常優雅。 :) – Crono
Dictionary
每個字母出現的#StringBuilder
通過輸入字符串信字母對應的存儲輸出我只是在寫你的答案時彈出來。 –
+1,這也是我的答案。 – Crono
試試這個:
var foundChars = new SortedDictionary<char, int>();
var stringBuilder = new StringBuilder();
foreach (var c in originalString)
{
var count = 0;
if (!foundChars.TryGetValue(c, out count)
{
foundChars.Add(c, 1);
}
else
{
count += 1;
foundChars[c] = count;
}
stringBuilder.Append(c);
if (count > 0) stringBuilder.Append(count);
}
注意的是,雖然不太漂亮,這將是比基於LINQ的解決方案更好的性能,並與retrocompatible .NET 2.0。
我會使用LINQ遍歷每個字符,然後保留一個你遇到的每個人的計數器。
例如..
var count = new Dictionary<string, int>();
var string = "abcdefabcdef";
var result = "";
string.Select().Each(c => {
if (count.ContainsKey(c))
count.Add(c, 1);
else
count[c]++;
result += count[c] > 1? c + count[c] : c;
});
一些其他的答案被O(n^2)
(Selman22,Stumblor)或O(n*log n)
(Chrono1981)遭受即使O(n)
解決方法很簡單。正確的解決方案真的是D Stanley和我暗示的。這裏是:
var input = "abcdefgabfabc";
var counts = new Dictionary<char, int>();
var sb = new StringBuilder();
foreach (var c in input)
{
int count;
counts.TryGetValue(c, out count); // If "counts" doesn't have the key, then count will be 0
counts[c] = ++count;
sb.Append(c);
if (count > 1)
sb.Append(count);
}
var result = sb.ToString();
我錯過了什麼?除了檢查'TryGetValue'的返回值和使用'SortedDictionary'外,我的代碼幾乎和你的一樣。 – Crono
提示:從'char'到'int'的'StringBuilder'和'Dictionary'。 –