私はほぼ正確にその問題を解決しようとしています。特に私はのような文字列s
を与えられ、それぞれは'A'
,'C'
,'T'
または'G'
のうちの1つです。私が置き換えることができる最小の部分文字列を見つけて、それぞれ'A'
,'C'
,'T'
、'G'
が正確にs.Length/4
回現れるようにしたい。例えば文字列が各文字の数と同じになるように置き換えることができる最小の部分文字列
は、s="GAAATAAA"
で一の最適解は"GTTCCGAA"
その結果、"TTCCG"
とサブ"AAATA"
を交換することです。
私は以下のコメントに私のアプローチを書いてきましたが、私はそれが正しい答えに私を得ることが遺伝的に正しいかどうか疑問に思っています。
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);
}
}
ソリューションは存在すると想定できますか?例えば。文字列 'AAB'は同じ数の' A'と 'B'を含む文字列に編集できません - このような場合は起こらないと保証されていますか? –
@j_random_hacker:長さは4で割り切れなければならない、私はそれが十分であるべきだと思う。また、この部分文字列のすべての文字を置き換える必要はないと思われます(このコメントから、 "GGTG" - > "AGCC"、第2インデックスの 'G 'は変更されません)。 – Groo
この方法では、残念ながら最悪の場合指数関数的な時間が必要になります。必要な部分文字列がO(n)の長さになる可能性があるからです(例はすべての 'T ' 'G'の終わりには、O(n)' C'と 'A'が任意の' T'と 'G'の間に現れるように)、あなたはすべての有効な部分文字列を生成してテストしています長さのオーダー。 –