【发布时间】:2016-12-17 02:12:50
【问题描述】:
我正在尝试解决一个几乎完全一样的问题。特别是给了我一个字符串s,这样s.Length % 4 == 0 和每个s[i] 是'A'、'C'、'T' 或'G' 之一。我想找到可以替换的最小子字符串,以便'A'、'C'、'T' 和'G' 中的每一个都恰好出现s.Length / 4 次。
例如,对于s="GAAATAAA",一种最佳解决方案是将子字符串"AAATA" 替换为"TTCCG",从而得到"GTTCCGAA"。
我在下面的 cmets 中描述了我的方法,我想知道它是否普遍正确,因为它会让我得到正确的答案。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
class Solution
{
static string ReplacementForSteadiness(string s)
{
var counter = new Dictionary<char,int>() {
{ 'A', 0 }, { 'C', 0 }, { 'G', 0 }, { 'T', 0 }
};
for(int i = 0; i < s.Length; ++i)
counter[s[i]] += 1;
int div = s.Length / 4;
var pairs = counter.ToList();
if(pairs.All(p => p.Value == div))
return "";
// If here, that means there is an even count of characters in s. For example, if
// s = "AAATGTTCTTGCGGGG", then counter = { A -> 3, T -> 5, C -> 2, G -> 6 },
// div = 4, and we know that we need to increase the number of As by 1, decrease
// the number of Ts by 1, increase the number of Cs by 2 and decrease the number
// of Gs by 2.
// The smallest strings to replace will have 1 T and 2 Gs, to be replaced with 1 A and
// 2 Cs (The order of characters in the replacement string doesn't matter).
// "TGG" --> "ACC"
// "GTG" --> "ACC"
// "GGT" --> "ACC"
// None of those strings exist in s. The next smallest strings that could be replaced
// would have 1 T and 3Gs, to be replaced with 1 A and 2 of the Gs to be replaced with
// Cs. Or, 2 Ts and 2Gs, 1 of the Ts to be replaced by an A and both the Gs to be replaced
// by Cs.
// "TGGG" --> "AGCC"
// "GTGG" --> "AGCC"
// "GGTG" --> "AGCC"
// "GGGT" --> "AGCC"
// "TTGG" --> "ATCC"
// "TGTG" --> "ATCC"
// "GTGT" --> "ATCC"
// "GGTT" --> "ATCC"
// None of those strings exist in s. Etc.
string r;
// ...
return r;
}
static void Main(String[] args)
{
Console.ReadLine(); // n
string str = Console.ReadLine();
string replacement = ReplacementForSteadiness(str);
Console.WriteLine(replacement.Length);
}
}
【问题讨论】:
-
这能回答你的问题吗? Bear and Steady gene - improve solution
标签: c# string algorithm time-complexity dynamic-programming