原题如下:
1632. Count email groups
Give you an array of n email addresses.
Find the number of email groups and each group should have more than one email address(the address can be duplicated). If two strings have the same value after being transformed, they are in the same group.
The rules of transforming are as follows:
Ignore all the characters ‘.’ before the character ‘@’.
Ignore the substring which starts with the first ‘+’(included) and ends with the character ‘@’(exclude).
Example
emails: [“abc.bc+c+d@jiuzhang.com”, "abcbc+d@jiuzhang.com", "abc.bc.cd@jiuzhang.com"]
count: 1
"abc.bc+c+d@jiuzhang.com" transforms to "abcbc@jiuzhang.com"
"abcbc+d@jiuzhang.com" transforms to "abcbc@jiuzhang.com"
"abc.bc.cd@jiuzhang.com" transforms to "abcbccd@jiuzhang.com"
We can see that the first address and the second address are in the same group, and there is no address can transform to the same address as the third one. Therefore, there is only one group which meets the requrements.
emails: [“abc.b+c+d@jiuzhang.com”, "abcbc+d@jiuzhang.com", "abc.bc.cd@jiuzhang.com"]
count: 0
There is no group meet the conditions.
Notice
a email group have at least two same email address(after transforming)
这题要注意字符串s的操作。如果s初始化的时候没有给定长度,用s[index++] = email[i]的操作是错的,只能用s = s + email[i]。
class Solution {
public:
/**
* @param emails: Original email
* @return: Return the count of groups which has more than one email address in it.
*/
int countGroups(vector<string> &emails) {
map<string, int> mp; //string, count
for (auto email : emails) {
string s;
int len = email.size();
bool foundPlus = false;
bool foundAt = false;
for (int i = 0; i < len; ++i) {
if (email[i] == '+') {
foundPlus = true;
continue;
}
if (email[i] == '@') {
foundAt = true;
foundPlus = false;
}
if (!foundAt) {
if (foundPlus) continue;
if (email[i] == '.') continue;
else {
s = s + email[i]; // s[index++] = email[i]; //wrong!!!
}
} else {
s = s + email[i];
}
}
if (mp.find(s) == mp.end()) mp[s] = 1;
else mp[s]++;
}
int count = 0;
for (auto m : mp) {
if (m.second > 1) count++;
}
return count;
}
};