使用 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