使用 C++ 按顺序打印字符串的所有不同字符
在这个问题中,我们得到一个字符串。我们的任务是按字符串中出现的顺序打印字符串的所有不同字符。
让我们举个例子来理解我们的问题:
Input: tutorials Point Output: uralsPn
解决此问题有多种方法,但我们将讨论最有效的方法。简单的方法包括循环嵌套。
为此,我们将使用两个大小为 256 的数组(存储 8 位字符)。
首先,我们将计数器数组的所有值初始化为 0,并将索引数组的所有值初始化为 n(字符串的长度)。遍历字符串 str,对于每个字符 c,增加 count[x],如果 count[x] = 1,则 index[x] = i。如果 count[x] = 2,则 index[x] = n。对索引进行排序并打印字符。
示例
显示我们解决方案实现的代码:
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 256;
void printDistinctCharacters(string str) {
int n = str.length();
int count[MAX_CHAR];
int index[MAX_CHAR];
for (int i = 0; i < MAX_CHAR; i++) {
count[i] = 0;
index[i] = n;
}
for (int i = 0; i < n; i++) {
char x=str[i];
++count[x];
if (count[x] == 1 && x !=' ')
index[x] = i;
if (count[x] == 2)
index[x] = n;
}
sort(index, index+MAX_CHAR);
for (int i=0; i<MAX_CHAR && index[i] != n; i++)
cout<<str[index[i]]<<" ";
}
int main() {
string str = "tutorialsPoint";
cout<<"All distinct Characters of the string '"<<str<<"' are :\n";
printDistinctCharacters(str);
return 0;
}输出
All distinct Characters of the string 'tutorialsPoint' are − u r a l s P n
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP