leetcode 1002. 查找常用字符

2020-10-31  本文已影响0人  Source_Chang

leetcode

C++:

class Solution {
public:
    vector<string> commonChars(vector<string>& A) {

        std::map<char, int> mapLastTime;
        for ( int i = 0; i < A.size(); ++i ) {

            std::map<char, int> mapThisTime;
            string temp = A[i];
            for ( int j = 0; j < temp.size(); ++j ) {

                char c = temp[j];
                if ( c >= 'a' && c <= 'z' ) {

                    if ( i == 0 ) {

                        ++mapThisTime[c];

                    } else {

                        if ( mapLastTime.find(c) != mapLastTime.end() && mapLastTime[c] > 0 ) {

                            --mapLastTime[c];
                            ++mapThisTime[c];
                        }
                    }
                }
            }
            mapLastTime = mapThisTime;
        }

        std::vector<std::string> arrResults;
        for ( auto c : mapLastTime ) {

            for ( int i = 0; i < c.second; ++i ) {

                std::string s(1, c.first);
                arrResults.push_back(s);
            }
        }

        return arrResults;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读