2014-09-27 2 views
-4

문자열에서 중복 문자를 제거하는 프로그램을 작성 중이고 이미 코드를 발견했지만 1 년 전에 게시되었지만 얻을 수없는 몇 가지 사항이 있습니다. understanding code that removes duplicate characters in a string (from cracking the coding interview)누군가이 기능을 설명해 주시겠습니까?

string remove_duplicates(string &s1) 
{ 
    int n=s1.size(); 
    for(int i=n-1; i!=-1; --i) 
    for(int j=0; j<i; ++j)   //why is j<i ? 
    { 
     if(s1[i]==s1[j]) 
     { 
      int k=i;    //What does the k do? 
      while(k!=n)   //Why do we use loop here? 
      { 
       s1[k]=s1[k+1]; //why is k=k+1 ? 
       k++; 
      } 
     } 
    } 
return s1; 
} 
+0

실행되고, 그것으로 어떻게 변화 하는지를 코드가 진행됨). –

+0

우선 문자열이 아니라 배열입니다. 두 번째로, 나는 이미 혼자서 그것을 알아내어 시험해 보았습니다. 그리고 그 이유를 모를 때 나는 그 질문을했습니다. 하지만 어쨌든 당신의 의견을 공유해 주셔서 감사합니다 :) – user4043493

+0

또한,이 코드는 실제로 작동하지 않습니다. –

답변

0

기능이 정확합니다. 설명문이 새겨 져 있습니다.

string remove_duplicates(string &s1) 
{ 
int n=s1.size(); 
for(int i=n-1; i!=-1; --i) 
    for(int j=0; j<i; ++j) // need to check if s1[i] has repeat till i-1 
    { 
    if(s1[i]==s1[j]) // repeat found 
    { 
    int k=i; // k stores the position of char repeated earlier 
    while(k!=n) // till end of the original string 
    { 
     s1[k]=s1[k+1]; // left shift all chars from repeat char till null terminating char 
     k++; 
    } 
    } 
    } 
    s1=s1.c_str(); 
    return s1; 
} 

int main() 
{ 
    cout << "Hello World" << endl; 
    string s = "abccbcd"; 
    cout << remove_duplicates(s).c_str() << endl; 
    return 0; 
} 

Result is: "abcd" (size = 4) 

"abccbcd는"즉 어레이의 내용을 도면을 그리는 ("abccbd"다음 "abccd"다음 "ABCD"손으로 몇 개의 간단한 예를 통해

+0

기능이 올바르지 않습니다. 문자열의 길이는 수정하지 않습니다. –

+0

Debasish 고맙습니다 :) – user4043493

+0

수정 된 크기를 다시 쓸 수 있지만이 기능의 목적은 중복 문자를 제거하는 것입니다. 어떻게 문자열을 줄일 수 있습니까? – user4043493

관련 문제