通过替换缺失位置的字符使字符串在每 K 个字符后重复
给定一个字符串S和整数K和 还有一些缺失的字符,即(_),任务是使 每K 个字符后重复的字符串S 通过在缺失的地方替换适当的字符,即(_)。如果不可能,则打印-1。
Note: If there are multiple possible strings, then print the smallest lexicographically string.
例子:
Input: S = ab_bab, K = 2
Output: ababab
Explanation:
Replace _ with ‘a’ and then the string will follow a repeating sequence after every 2 characters.
Input: S = _b_abc_bc, K = 3
Output: abcabcabc
方法:这个问题可以通过遍历字符串S来解决。请按照以下步骤解决此问题:
- 用NULL字符初始化大小为K的数组arr[] 。
- 使用变量i在[0, K-1]范围内迭代:
- 使用增量为K的变量j在[i, N-1]范围内迭代:
- 如果不缺少字符,则用当前字符填充数组arr[i] 。
- 否则,如果字符既不匹配数组arr[]也不匹配K出现模式,则返回-1 。
- 如果数组arr[]最初具有NULL值,即未找到任何K出现模式,则按字典顺序填充最小字符,即“ a ”。
- 使用增量为K的变量j在[i, N-1]范围内迭代:
- 用所有值“ a ”初始化大小为n的数组ans[] 。
- 使用变量i在[0, N]范围内迭代并将ans[i] 更新为 arr[i%K]
- 最后,将这个ans数组转换成字符串并返回这个。
下面是上述方法的实现:
Python3
# Creating function findMissingChar having parameter
# n i.e length of the string
# k is repeating occurrence of character
# s is given string
def findMissingChar(n, k, s):
# Creating an array arr of size K,
# initially with NULL values.
arr = ['']*k
# Iterate for loop from 0 to k-1.
for i in range(k):
# Iterate for loop from i to n
# with increment of k.
for j in range(i, n, k):
# If it is not missing character
# then fill array arr[i]
# with current character.
if s[j] != '_':
if arr[i] == '':
arr[i] = s[j]
else:
# If character is neither matched
# with a array or k occurrence pattern
# return -1 in this case.
if s[j] != arr[i]:
return -1
# If the array having initially null values
# i.e haven't found any k occurrence pattern
# then fill lexicographically
# the smallest character i.e 'a'.
if arr[i] == '':
arr[i] = 'a'
# Creating ans array having size n
# and initialize with 'a'.
ans = ['a']*n
# Filling ans array with suitable
# lexicographically smallest character.
for i in range(n):
ans[i] = arr[i % k]
return ''.join(ans)
# Driver Code
s = '_b_abc_bc'
n = len(s)
k = 3
print(findMissingChar(n, k, s))
Javascript
输出:
abcabcabc
时间复杂度: O(N*K)
辅助空间: O(N)