ในปัญหานี้ เราได้รับสตริง งานของเราคือพิมพ์อักขระที่แตกต่างกันทั้งหมดของสตริงตามลำดับที่ปรากฏในสตริง
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหาของเรากัน
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