花了好些时间才写出来,有更简单的方法是干脆用了两个标记,一个标记是否访问过,一个标记是否是第一次访问。我这个未免有点复杂了。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string s;
cin>>s;
int n = s.length();
vector<int> flag(n,0);
vector<int> temp;
vector<vector<int>> showTime;//每个重复字符出现的下标都用一个vector存储
for (int i = 0; i < n; i++)
{
if (flag[i] != 0) continue;//标记不为0,说明已经访问过
while (!temp.empty())
temp.pop_back();
for (int j = i + 1; j < s.length(); j++)
{
if (s[i] == s[j])
{
temp.push_back(i);//i会重复输入,所以输出时是+2
temp.push_back(j);
flag[j] = 1;//访问过打上标记
}
}
if(!temp.empty()) showTime.push_back(temp);
}
for (int i = 0; i < showTime.size();i++) {
cout << s[showTime[i][0]] << ":" << showTime[i][0] << ",";
for (int j = 1; j < showTime[i].size(); j=j+2) {
cout << s[showTime[i][j]]<<":"<< showTime[i][j];
if (j != showTime[i].size() - 1)cout << ",";
}
cout << endl;
}
}
接下来用两个标记实现,并且在输出处巧妙处理一下输出“,”的位置,便可以避免对末尾处逗号输出的讨论了,这个经验要记住!
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string s;
cin>>s;
int n = s.length();
vector<int> flag(n,0);
bool isfirst=true;
for (int i = 0; i < n; i++)
{
if (flag[i] != 0) continue;//标记不为0,说明已经访问过
isfirst=true;
for (int j = i + 1; j < s.length(); j++)
{
if (s[i] == s[j])
{
if(isfirst){
isfirst=false;
cout<<s[i]<<":"<<i;//不在这里输出逗号
}
cout<<","<<s[j]<<":"<<j;//在这里输出逗号
flag[j] = 1;//访问过打上标记
}
}
if(!isfirst)cout<<endl;
}
}