LintCode 1632: Count email group

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/roufoo/article/details/84927477

原题如下:
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: [“[email protected]”, "[email protected]", "[email protected]"]

count: 1

"[email protected]" transforms to "[email protected]"
"[email protected]" transforms to "[email protected]"
"[email protected]" transforms to "[email protected]"
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: [“[email protected]”, "[email protected]", "[email protected]"]

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

猜你喜欢

转载自blog.csdn.net/roufoo/article/details/84927477