有人能解释一下这个功能吗
Can someone please explain this function?
我正在编写一个从字符串中删除重复字符的程序,我已经找到了代码,它是一年前发布的,但有一些东西我没有得到。理解删除字符串中重复字符的代码(来自破解编码面试)
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"
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 有人能分解一下这个c++模板的语法吗
- 带内存和隔离功能的SQLite
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- QML按钮点击功能执行顺序
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 有没有可能有一个只有ADL才能找到的非好友功能
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 文件系统:复制功能的速度秘诀是什么
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 有人可以解释一下复制功能的作用吗?
- 有人能解释一下这个功能是如何工作的吗
- 有人能用WinSock解释一下可写可读的fd_sets的功能吗
- 有人能解释一下这个功能吗