【KingdaoComputerTest】-検索-場所の検索-華中科技大学

書き出すのに時間がかかりました。簡単な方法は、2つのタグを使用することです。一方が訪問されたかどうか、もう一方が最初の訪問かどうかです。これは私にとって少し複雑です。

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

次に、2つのマーカーを使用して、出力の「、」の位置を達成し、巧妙に処理して、最後のコンマ出力の説明を回避します。この経験を覚えておく必要があります。

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

	
}

 

おすすめ

転載: blog.csdn.net/qq_39328436/article/details/114583669