Share my C++ code with just one loop


  • 1
    P

    Here I use 'N' adding to the front of the string to decide whether it has been searched.

      class Solution {
        public:
            vector<string> anagrams(vector<string> &strs) {
                unordered_map<string,string> mp;
                vector<string> vec;
                for(auto e:strs)
                {
                    //t is a sorted string
                    string t=e;
        			if(!t.empty())
        				sort(t.begin(),t.end());
                    //The added 'N' means 'never been searched'
                    if(mp.find(t)==mp.end())
                        mp.insert(make_pair(t,'N'+e));
                    else
                    {
        				if(!mp[t].empty()&&mp[t].front()=='N')
                        {
                            mp[t]=mp[t].substr(1);
                            vec.push_back(mp[t]);
                        }
                        vec.push_back(e);
                    }
                }
                return vec;
                
            }
        };

  • 0
    E

    i just had the same thought as you, but i got a "Output Limit Exceeded" error, now i am confused


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.