3474. Lexicographically Smallest Generated String
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
using System.Text;
|
||||
|
||||
public class Solution
|
||||
{
|
||||
public string GenerateString(string str1, string str2)
|
||||
{
|
||||
var len = str1.Length + str2.Length - 1;
|
||||
var answer = new char[len];
|
||||
|
||||
// Сначала обработать все T
|
||||
for (var i = 0; i < str1.Length; i++)
|
||||
{
|
||||
if (str1[i] == 'T')
|
||||
{
|
||||
var sbIdx = i;
|
||||
for (var j = 0; j < str2.Length; j++)
|
||||
{
|
||||
if (answer[sbIdx] != 0 && answer[sbIdx] != str2[j])
|
||||
return "";
|
||||
answer[sbIdx++] = str2[j];
|
||||
}
|
||||
}
|
||||
}
|
||||
// Теперь обработать все F
|
||||
var canChange = new bool[len];
|
||||
var lastF = -1;
|
||||
for (var i = 0; i < str1.Length; i++)
|
||||
if (str1[i] == 'F')
|
||||
{
|
||||
if (ProcessF(answer.AsSpan()[i..(i + str2.Length)], str2, canChange.AsSpan()[i..(i + str2.Length)], out var goBack) == false)
|
||||
return "";
|
||||
if(goBack && lastF != -1)
|
||||
i = lastF - 1;
|
||||
else
|
||||
lastF = i;
|
||||
}
|
||||
|
||||
return new string(answer);
|
||||
}
|
||||
|
||||
private bool ProcessF(Span<char> chars, string s2, Span<bool> canChange, out bool goBack)
|
||||
{
|
||||
goBack = false;
|
||||
|
||||
var equal = true;
|
||||
var emptyCount = 0;
|
||||
var hasDiff = false;
|
||||
var lastCanChange = -1;
|
||||
for (var i = 0; i < s2.Length; i++)
|
||||
{
|
||||
equal &= chars[i] == s2[i];
|
||||
if (chars[i] == 0)
|
||||
emptyCount++;
|
||||
else if (chars[i] != s2[i])
|
||||
hasDiff = true;
|
||||
if (canChange[i])
|
||||
lastCanChange = i;
|
||||
}
|
||||
if (equal)
|
||||
{
|
||||
if (lastCanChange >= 0)
|
||||
{
|
||||
chars[lastCanChange]++;
|
||||
if (chars[lastCanChange] == 'z' + 1)
|
||||
chars[lastCanChange] = 'a';
|
||||
goBack = true;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
for (var i = 0; i < chars.Length && emptyCount > 0; i++)
|
||||
{
|
||||
if (chars[i] != 0)
|
||||
continue;
|
||||
var insert = 'a';
|
||||
if (emptyCount == 1 && s2[i] == insert && !hasDiff)
|
||||
insert++;
|
||||
chars[i] = insert;
|
||||
canChange[i] = true;
|
||||
if (s2[i] != insert)
|
||||
hasDiff = true;
|
||||
emptyCount--;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user