有人能解释一下这个功能吗

Can someone please explain this function?

本文关键字:一下 功能 能解释      更新时间:2023-10-16

我正在编写一个从字符串中删除重复字符的程序,我已经找到了代码,它是一年前发布的,但有一些东西我没有得到。理解删除字符串中重复字符的代码(来自破解编码面试)

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;
}

函数是正确的。以题字注释形式给出的解释。

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"