이 문제에서는 문자열이 제공됩니다. 우리의 임무는 문자열에 나타나는 순서대로 문자열의 모든 고유한 문자를 인쇄하는 것입니다.
문제를 이해하기 위해 예를 들어 보겠습니다.
Input: tutorials Point Output: uralsPn
이 문제를 해결하는 방법은 여러 가지가 있지만 가장 효과적인 방법에 대해 설명합니다. 간단한 것은 루프의 중첩을 포함합니다.
이를 위해 크기가 256인 두 개의 배열(8비트 문자가 저장됨)을 사용합니다.
먼저 카운터 배열의 모든 값을 0으로 초기화하고 인덱스 배열의 모든 값을 n(문자열 길이)으로 초기화합니다. 문자열 str을 순회할 때 모든 문자 c에 대해 count[x] =1, index[x] =i이면 count[x]를 늘립니다. 개수[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