字符串范围查询,统计包含更新后的不同字符数量
字符串范围查询是指字符串中存在的字符范围,其中字符从索引[0]开始,最后一个索引[]可以根据给定字符串的长度指定。在本文中,我们将学习字符串范围查询如何统计包含更新后的不同字符数量。
让我们以一个统计字符串及其更新后不同字符数量的例子为例。
字符串 = “tutorialpoint” // 原始字符串
给定字符串的长度为 12。因此,计数为 13(计数始终从 1 开始)。
如果我们在 'l' 之后添加字符 's',则长度将变为 13,计数为 14。
现在更新后的字符串为 tutorialspoint。
要统计更新后字符串的不同字符,它变为 **10**,因为不同的字符只出现一次。例如,“tt”在**区分**后总共有两个字符,它变为 1。
语法
unordered_map < datatype, string > Map_Name
参数
**unordered_map** - 这是 c++ 的标准模板库,用于存储包含键值对的元素。
**数据类型** - 数据类型表示为键,这是用户指定的数据类型。
**字符串** - 字符串表示为值。
**Map_Name** - 为映射指定的任何名称。
.first .second
参数
.first - 表示字符串对的第一部分。
.second - 表示字符串对的第二部分。
算法
我们将从名为 **'iostream'** 和 **'unordered_map'** 的头文件开始程序。
现在,我们从主函数开始,初始化一个空的 **'unordered_map <char, int>'** 来存储给定字符串中每个字符的计数。
我们使用第一个 for 循环逐个遍历字符串字符 **(charCount++)**。
我们使用第二个 for 循环打印不同的字符及其计数。在这个循环中,我们打印以下内容 -
p.first - 打印字符串的字符。
p.second - 这将计算每个字符条目出现的次数。
完成第二个 for 循环后,我们将第三个索引更新为 **p** 以获取新更新的字符串及其计数。接下来,使用字符串上的 **[]** 简单地修改先前索引的字符串字符。然后通过递减旧字符的计数来更新映射上的计数 **[l--]**,并借助 **[p++]** 将新字符递增到字符串中。
最后,我们打印不同的字符及其计数和更新后的字符串。
示例
在这个程序中,我们将找到字符串范围查询以统计包含更新后的不同字符数量。
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
string s = "school";
// counting of distinct characters in a string
unordered_map<char, int> charCount;
for (char c : s) {
charCount[c]++;
}
cout << "The Distinct characters of the string: ";
for (auto p : charCount) {
cout << p.first << "(" << p.second << ")\t ";
}
cout << endl;
//updation of string count and character distinction
s[3] = 'p';
// user can use any character
charCount['l']--;
charCount['p']++;
cout<< "*********:After Updation:*********";
// print the distinct characters along with their count
cout <<"\n"<< "The Distinct characters of the updated string: ";
for (auto p : charCount) {
cout << p.first << " (" << p.second << ")\t ";
}
cout << endl;
return 0;
}
输出
The Distinct characters of the string: l(1) o(2) h(1) c(1) s(1) *********:After Updation:********* The Distinct characters of the updated string: l (0) o (2) h (1) p (1) c (1) s (1)
结论
我们已经探索了字符串范围查询的概念,以统计包含更新后的不同字符数量。我们在输出中看到,它通过进行区分来反向统计字符串的字符。例如,很多时候我们有两件相同颜色的衬衫,但我们只穿其中一件,这展示了区分的一个现实生活例子。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP