在C ++中按顺序打印字符串的所有不同字符
在这个问题上,我们得到一个字符串。我们的任务是按字符串中出现的所有不同字符的顺序打印。
让我们举一个例子来了解我们的问题,
Input: tutorials Point Output: uralsPn
解决此问题的方法有多种,但我们将讨论最有效的一种。最简单的方法包括嵌套循环。
为此,我们将使用两个大小为256(存储8位字符)的数组。
首先,我们将计数器数组的所有值初始化为0,并将索引数组的所有值初始化为n(字符串的长度)。在遍历字符串str时,对于每个字符c,如果count[x]=1,则增加count[x],index[x]=i。如果count[x]=2,则索引[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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短