找位置
找位置
http://www.nowcoder.com/questionTerminal/e3b2cc44aa9b4851bdca89dd79c53150
题目
对给定的一个字符串,找出有重复的字符,并给出其位置,如:abcaaAB12ab12 输出:a,1;a,4;a,5;a,10,b,2;b,11,1,8;1,12, 2,9;2,13。
//使用map + vector的方法吧 #include <iostream> #include <map> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { string str; while(cin>>str) { map<char, vector<int>> mp; vector<char> v; for(int i = 0; i < str.size(); i++) { if (mp.find(str[i]) != mp.end()) { //existed mp[str[i]].push_back(i); } else { vector<int> add; add.push_back(i); mp[str[i]] = add; v.push_back(str[i]); } } // sort(v.begin(), v.end()); for (int i = 0; i < v.size(); i++) { if (mp[v[i]].size() > 1) { for (int j = 0; j < mp[v[i]].size() - 1; j++) { cout<<v[i]<<":"<<mp[v[i]][j]<<","; } cout<<v[i]<<":"<<mp[v[i]][mp[v[i]].size() - 1]; cout<<endl; } } } return 0; }