没有给定前缀的 N 位数字的计数
给定一个整数N和一个字符串前缀向量 [],任务是计算从字符'0'到'9'的长度为N的总可能字符串。这样给定的前缀不能在任何字符串中使用。
例子:
Input: N = 3, prefixes = {“42”}
Output: 990
Explanation: All string except{“420”, “421”, “422”, “423”, “424”, “425”, “426”, “427”, “428”, “429”} are valid.
Input: N = 5, prefixes[] = { “0”, “1”, “911” }
Output: 79900
方法:长度可能的字符串总数为(10^N) ,因为字符串中的每个位置都有10 个字符的选择。不是计算总的好字符串,而是从总字符串。在迭代前缀之前 合并具有与较大长度前缀相同的起始字符的前缀可能会导致减去一些重复。请按照以下步骤解决问题:
- 将变量total初始化为10 N 。
- 初始化一个 map
> mp[]。 - 使用变量i遍历范围[0, M)并执行以下任务:
- 将prefixes[i]的值推入map mp[prefixes[i]-'0']的向量中。
- 初始化向量new_prefixes[] 。
- 使用变量x遍历映射mp[]并执行以下任务:
- 将变量mn初始化为N 。
- 使用变量p遍历向量x.second并执行以下任务:
- 将mn的值设置为mn或p.length()的最小值。
- 使用变量p遍历向量x.second并执行以下任务:
- 如果p.length()小于等于mn,则将p推入向量new_prefixes[] 。
- 使用变量i遍历范围[0, new_prefixes.size())并执行以下任务:
- 从变量total 中减去值int(pow(10, N – new_prefixes[i].length())+ 0.5) 。
- 执行上述步骤后,打印总的值作为答案。
下面是上述方法的实现:
C++
// C++ Program to implement the above approach
#include
using namespace std;
// Change int to long long in case of overflow!!
// Function to calculate total strings of length
// N without the given prefixes
int totalGoodStrings(int N, vector prefixes)
{
// Calculate total strings present
int total = int(pow(10, N) + 0.5);
// Make a map and insert the prefixes with same
// character in a vector
map > mp;
for (int i = 0; i < prefixes.size(); i++) {
mp[prefixes[i][0] - '0']
.push_back(prefixes[i]);
}
// Make a new vector of prefixes strings
vector new_prefixes;
// Iterate for each starting character
for (auto x : mp) {
int mn = N;
// Iterate through the vector to calculate
// minimum size prefix
for (auto p : x.second) {
mn = min(mn, int(p.length()));
}
// Take all the minimum prefixes in the new
// vector of prefixes
for (string p : x.second) {
if (p.length() > mn) {
continue;
}
new_prefixes.push_back(p);
}
}
// Iterate through the new prefixes
for (int i = 0; i < new_prefixes.size(); i++) {
// Subtract bad strings
total -= int(pow(10,
N - new_prefixes[i].length())
+ 0.5);
}
return total;
}
// Driver Code
int main()
{
int N = 5;
vector prefixes
= { "1", "0", "911" };
cout << totalGoodStrings(N, prefixes);
return 0;
}
Java
// Java Program to implement the above approach
import java.util.ArrayList;
import java.util.HashMap;
class GFG
{
// Change int to long long in case of overflow!!
// Function to calculate total strings of length
// N without the given prefixes
public static int totalGoodStrings(int N, String[] prefixes) {
// Calculate total strings present
int total = (int) (Math.pow(10, N) + 0.5);
// Make a map and insert the prefixes with same
// character in a vector
HashMap> mp = new HashMap>();
for (int i = 0; i < prefixes.length; i++) {
int key = (int) prefixes[i].charAt(0) - (int) '0';
if (mp.containsKey(key)) {
ArrayList temp = mp.get(key);
temp.add(prefixes[i]);
mp.put(key, temp);
} else {
ArrayList temp = new ArrayList();
temp.add(prefixes[i]);
mp.put(key, temp);
}
}
// Make a new vector of prefixes strings
ArrayList new_prefixes = new ArrayList();
// Iterate for each starting character
for (Integer x : mp.keySet()) {
int mn = N;
// Iterate through the vector to calculate
// minimum size prefix
for (String p : mp.get(x)) {
mn = Math.min(mn, p.length());
}
// Take all the minimum prefixes in the new
// vector of prefixes
for (String p : mp.get(x)) {
if (p.length() > mn) {
continue;
}
new_prefixes.add(p);
}
}
// Iterate through the new prefixes
for (int i = 0; i < new_prefixes.size(); i++) {
// Subtract bad strings
total -= (int) (Math.pow(10, N - new_prefixes.get(i).length()) + 0.5);
}
return total;
}
// Driver Code
public static void main(String args[])
{
int N = 5;
String[] prefixes = { "1", "0", "911" };
System.out.println(totalGoodStrings(N, prefixes));
}
}
// This code is contributed by gfgking.
Python3
# python Program to implement the above approach
import math
# Change int to long long in case of overflow!!
# Function to calculate total strings of length
# N without the given prefixes
def totalGoodStrings(N, prefixes):
# Calculate total strings present
total = int(math.pow(10, N) + 0.5)
# Make a map and insert the prefixes with same
# character in a vector
mp = {}
for i in range(0, len(prefixes)):
if (ord(prefixes[i][0]) - ord('0')) in mp:
mp[ord(prefixes[i][0]) - ord('0')].append(prefixes[i])
else:
mp[ord(prefixes[i][0]) - ord('0')] = [prefixes[i]]
# Make a new vector of prefixes strings
new_prefixes = []
# Iterate for each starting character
for x in mp:
mn = N
# Iterate through the vector to calculate
# minimum size prefix
for p in mp[x]:
mn = min(mn, len(p))
# Take all the minimum prefixes in the new
# vector of prefixes
for p in mp[x]:
if (len(p) > mn):
continue
new_prefixes.append(p)
# Iterate through the new prefixes
for i in range(0, len(new_prefixes)):
# Subtract bad strings
total -= int(pow(10, N - len(new_prefixes[i])) + 0.5)
return total
# Driver Code
if __name__ == "__main__":
N = 5
prefixes = ["1", "0", "911"]
print(totalGoodStrings(N, prefixes))
# This code is contributed by rakeshsahni
C#
// C# Program to implement the above approach
using System;
using System.Collections.Generic;
class GFG {
// Change int to long long in case of overflow!!
// Function to calculate total strings of length
// N without the given prefixes
public static int totalGoodStrings(int N,
string[] prefixes)
{
// Calculate total strings present
int total = (int)(Math.Pow(10, N) + 0.5);
// Make a map and insert the prefixes with same
// character in a vector
Dictionary > mp
= new Dictionary >();
for (int i = 0; i < prefixes.Length; i++) {
int key = (int)prefixes[i][0] - (int)'0';
if (mp.ContainsKey(key)) {
List temp = mp[key];
temp.Add(prefixes[i]);
mp[key] = temp;
}
else {
List temp = new List();
temp.Add(prefixes[i]);
mp[key] = temp;
}
}
// Make a new vector of prefixes strings
List new_prefixes = new List();
// Iterate for each starting character
foreach(int x in mp.Keys)
{
int mn = N;
// Iterate through the vector to calculate
// minimum size prefix
foreach(string p in mp[x])
{
mn = Math.Min(mn, p.Length);
}
// Take all the minimum prefixes in the new
// vector of prefixes
foreach(string p in mp[x])
{
if (p.Length > mn) {
continue;
}
new_prefixes.Add(p);
}
}
// Iterate through the new prefixes
for (int i = 0; i < new_prefixes.Count; i++) {
// Subtract bad strings
total
-= (int)(Math.Pow(
10, N - new_prefixes[i].Length)
+ 0.5);
}
return total;
}
// Driver Code
public static void Main(string[] args)
{
int N = 5;
string[] prefixes = { "1", "0", "911" };
Console.WriteLine(totalGoodStrings(N, prefixes));
}
}
// This code is contributed by ukasp.
Javascript
// Javascript Program to implement the above approach
// Change int to long long in case of overflow!!
// Function to calculate total strings of length
// N without the given prefixes
function totalGoodStrings(N, prefixes) {
// Calculate total strings present
let total = Math.floor(Math.pow(10, N) + 0.5);
// Make a map and insert the prefixes with same
// character in a vector
let mp = new Map();
for (let i = 0; i < prefixes.length; i++) {
let key = prefixes[i][0] - '0'.charCodeAt(0);
if (mp.has(key)) {
let temp = mp.get(key);
temp.push(prefixes[i])
mp.set(key, temp)
} else {
mp.set(key, [prefixes[i]])
}
}
// Make a new vector of prefixes strings
let new_prefixes = [];
// Iterate for each starting character
for (x of mp) {
let mn = N;
// Iterate through the vector to calculate
// minimum size prefix
for (p of x[1]) {
mn = Math.min(mn, p.length);
}
// Take all the minimum prefixes in the new
// vector of prefixes
for (p of x[1]) {
if (p.length > mn) {
continue;
}
new_prefixes.push(p);
}
}
// Iterate through the new prefixes
for (let i = 0; i < new_prefixes.length; i++) {
// Subtract bad strings
total -= Math.floor(Math.pow(10, N - new_prefixes[i].length) + 0.5);
}
return total;
}
// Driver Code
let N = 5;
let prefixes = ["1", "0", "911"];
document.write(totalGoodStrings(N, prefixes))
// This code is contributed by saurabh_jaiswal.
输出
79900
时间复杂度: O(M),其中 M 是向量前缀[]的大小
辅助空间: O(M*K),其中 K 是字符串的最大长度