📌  相关文章
📜  通过插入字符修改字符串,使得每个 K 长度的子字符串只包含唯一的字符

📅  最后修改于: 2021-10-27 07:13:10             🧑  作者: Mango

给定大小为N 的字符串SK 个不同的字符和(N – K) ‘?’ 组成s,任务是替换所有‘?’使用字符串的现有字符,使得每个大小为K 的子字符串仅由唯一字符。如果无法这样做,则打印“-1”

例子:

方法:这个想法是基于观察到在最终结果字符串,每个字符必须恰好出现在K 个位置之后,例如第(K + 1)字符必须与1相同,(K + 2)字符必须与2 nd相同,依此类推。

请按照以下步骤解决问题:

  • 初始化一个 hashmap M来存储字符的位置。
  • 使用变量i遍历字符串S ,如果当前字符S[i]与 ‘ 不同 ‘,然后更新M[i % K] = S[i]
  • 使用变量i遍历字符串S ,如果映射 M 中不存在i%k的值,则打印“-1”并退出循环。否则将S[i]更新为M[i % K]
  • 完成上述步骤后,如果循环没有中断,则将S作为结果字符串打印。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to replace all '?'
// characters in a string such
// that the given conditions are satisfied
void fillString(string s, int k)
{
    unordered_map mp;
 
    // Traverse the string to Map the
    // characters with respective positions
    for (int i = 0; i < s.size(); i++) {
        if (s[i] != '?') {
            mp[i % k] = s[i];
        }
    }
 
    // Traverse the string again and
    // replace all unknown characters
    for (int i = 0; i < s.size(); i++) {
 
        // If i % k is not found in
        // the Map M, then return -1
        if (mp.find(i % k) == mp.end()) {
 
            cout << -1;
            return;
        }
 
        // Update S[i]
        s[i] = mp[i % k];
    }
 
    // Print the string S
    cout << s;
}
 
// Driver Code
int main()
{
    string S = "????abcd";
    int K = 4;
    fillString(S, K);
 
    return 0;
}


Java
// Java Program to implement
// the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to replace all '?'
    // characters in a string such
    // that the given conditions are satisfied
    static void fillString(String str, int k)
    {
 
        char s[] = str.toCharArray();
 
        HashMap mp = new HashMap<>();
 
        // Traverse the string to Map the
        // characters with respective positions
        for (int i = 0; i < s.length; i++) {
            if (s[i] != '?') {
                mp.put(i % k, s[i]);
            }
        }
 
        // Traverse the string again and
        // replace all unknown characters
        for (int i = 0; i < s.length; i++) {
 
            // If i % k is not found in
            // the Map M, then return -1
            if (!mp.containsKey(i % k)) {
                System.out.println(-1);
                return;
            }
 
            // Update S[i]
            s[i] = mp.getOrDefault(i % k, s[i]);
        }
 
        // Print the string S
        System.out.println(new String(s));
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        String S = "????abcd";
        int K = 4;
        fillString(S, K);
    }
}
 
// This code is contributed by Kingash.


Python3
# Python 3 program for the above approach
 
# Function to replace all '?'
# characters in a string such
# that the given conditions are satisfied
def fillString(s, k):
    mp = {}
 
    # Traverse the string to Map the
    # characters with respective positions
    for i in range(len(s)):
        if (s[i] != '?'):
            mp[i % k] = s[i]
 
    # Traverse the string again and
    # replace all unknown characters
    s = list(s)
    for i in range(len(s)):
       
        # If i % k is not found in
        # the Map M, then return -1
        if ((i % k) not in mp):
            print(-1)
            return
 
        # Update S[i]
        s[i] = mp[i % k]
 
    # Print the string S
    s =   ''.join(s)
    print(s)
 
# Driver Code
if __name__ == '__main__':
    S = "????abcd"
    K = 4
    fillString(S, K)
 
    # This code is contributed by bgangwar59.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to replace all '?'
  // characters in a string such
  // that the given conditions are satisfied
  static void fillString(string str, int k)
  {
 
    char[] s = str.ToCharArray();
 
    Dictionary mp = new Dictionary();
 
    // Traverse the string to Map the
    // characters with respective positions
    for (int i = 0; i < s.Length; i++) {
      if (s[i] != '?') {
        mp[i % k] = s[i];
      }
    }
 
    // Traverse the string again and
    // replace all unknown characters
    for (int i = 0; i < s.Length; i++) {
 
      // If i % k is not found in
      // the Map M, then return -1
      if (!mp.ContainsKey(i % k)) {
        Console.WriteLine(-1);
        return;
      }
 
      // Update S[i]
      s[i] = (char)mp[i % k];
 
    }
 
    // Print the string S
    Console.WriteLine(new string(s));
  }
 
  // Driver code
  static void Main()
  {
    string S = "????abcd";
    int K = 4;
    fillString(S, K);
  }
}
 
// This code is contributed by susmitakundugoaldanga.


Javascript


输出:
abcdabcd

时间复杂度: O(N)
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程