我正在编写一个程序来删除字符串中的重复字符,我已经找到了代码,它是在一年前发布的,但有一些我没有得到的东西。 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)
功能正确。 作为铭文评论给出的解释。
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)
&#34; abccbcd&#34;成为&#34; abccbd&#34;然后&#34; abccd&#34;然后&#34; abcd&#34;