使所有子字符串不同的字符串的最小更改
字符串是一种特定的对象,它表示数据字符的序列和流。字符串是数据容器,始终以文本格式表示。它还用于概念、比较、拆分、连接、替换、修剪、长度、内部化、相等、比较、子字符串操作。substring() 是一种数据细化过程,它从起始位置到结束位置提取两个位置之间保存的数据。substring() 不会更改原始字符串。在一个数据集中,当我们有不同的字符时,它们可以表示为不同的数据元素。例如:'a' 和 'r' 是不同的,而 'r' 和 'r' 是相同的。因此,一个字符串,比如 orange,包含 6 个不同的字符。同样,字符串 apple 只包含 4 个不同的字符。
假设 "s" 是一个字符串,我们需要找到对所有子字符串进行更改以使其成为不同字符串所需的最小更改次数。
字符串长度 - 26
给定输入 - T 是第一行上的测试用例,包含一个整数。对于每个测试用例,只有一行包含 26 个字符。
输出 - 我们将获得每个测试用例的最小更改次数。
逻辑方法过程的约束
1 <= T <= 100
1 <= |s| <= 26
在本文中,我们将学习如何对字符串进行更改以使所有子字符串都不同。
使子字符串不同的算法
以下是通过进行最小更改使字符串的所有子字符串都不同的可能算法。
步骤 1 - 开始。
步骤 2 - 使用两个嵌套循环生成子字符串。
步骤 3 - 外部循环从 i = 0 到字符串长度减 1。
步骤 4 - 内部循环从 j = 0 到字符串长度减 1。
步骤 5 - 使用零值构建计数变量。
步骤 6 - 在外部循环内,创建一个 distinct_character 变量。
步骤 7 - 创建频率数组。
步骤 8 - 将所有元素设置为零。
步骤 9 - 检查字符串[j] - 'a' 的频率是否为零。
步骤 10 - 如果为零,则将其递增 1。
步骤 11 - 否则,将其分解成内部循环。
步骤 12 - 如果计数大于零,则返回计数。
步骤 13 - 否则,返回 -1。
步骤 14 - 终止。
创建所有不同子字符串的语法
string.substring(start, end)
在此语法中,我们可以看到如何对字符串进行最小更改以使所有子字符串都不同。
参数
开始 - 需要声明一个起始位置。这里第一个字符位于索引 0。
结束 - 这是一个可选的过程,位于结束位置(直到但不包括)。
方法
方法 1 - 找到对其进行的最小更改次数,以便字符串的所有子字符串都变得不同。
找到对其进行的最小更改次数,以便字符串的所有子字符串都变得不同
在此方法中,我们将学习如何使所有子字符串都不同。这里每个字符都必须不同。我们只需要找出字符的数量。如果字符串长度大于 26,那么我们只需要将其转换为字符串。在这里,我们将相同的逻辑写入不同的语言环境。
示例 1:使用 C++
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
int minChanges(string &str) {
int n = str.length();
if (n > MAX_CHAR)
return -1;
int dist_count = 0;
int count[MAX_CHAR] = {0};
for (int i = 0; i < n; i++) {
if (count[str[i] - 'a'] == 0)
dist_count++;
count[(str[i] - 'a')]++;
}
return (n - dist_count);
}
int main() {
string str = "aebaecedabbeedee";
cout << minChanges(str);
return 0;
}
输出
11
示例 2:使用 Java
import java.lang.*;
import java.util.*;
public class tutorialspoint {
static final int MAX_CHAR = 26;
public static int minChanges(String str) {
int n = str.length();
if (n > MAX_CHAR)
return -1;
int dist_count = 0;
int count[] = new int[MAX_CHAR];
for(int i = 0; i < MAX_CHAR; i++)
count[i] = 0;
for (int i = 0; i < n; i++) {
if(count[str.charAt(i)-'a'] == 0)
dist_count++;
count[str.charAt(i)-'a']++;
}
return (n-dist_count);
}
public static void main (String[] args) {
String str = "aebaecedabbeedee";
System.out.println(minChanges(str));
}
}
输出
11
示例 1:使用 Python
MAX_CHAR = [26]
def minChanges(str):
n = len(str )
if (n > MAX_CHAR[0]):
return -1
dist_count = 0
count = [0] * MAX_CHAR[0]
for i in range(n):
if (count[ord(str[i]) - ord('a')] == 0) :
dist_count += 1
count[(ord(str[i]) - ord('a'))] += 1
return (n - dist_count)
if __name__ == '__main__':
str = "aebaecedabbeedee"
print(minChanges(str))
输出
11
结论
今天,在本文中,我们学习了如何通过对其进行最小更改来使所有子字符串都不同。在这里,我们根据提到的算法在 C++、Java 和 Python 中创建了一些可能的代码。希望这将帮助您更全面地了解此主题。
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP