【Kingdao Computer Test】-Find-Find Location-Huazhong University of Science and Technology

It took a long time to write it out. An easier way is to simply use two tags, whether one has been visited, and whether the other is the first visit. This is a bit complicated for me.

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

Next, use two markers to achieve, and cleverly handle the position of the output "," at the output, to avoid the discussion of the comma output at the end, this experience should be remembered!

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

	
}

 

Guess you like

Origin blog.csdn.net/qq_39328436/article/details/114583669