LeetCode OJ--Anagrams **

https://oj.leetcode.com/problems/anagrams/

在一个vector<string>中,找到所有经过顺序变换,可以变成一样的 string.

首先,对每个 string 排序,这样它的顺序就是 abcd 相当于做了一个统一。

然后,对vector排序,这样,如果有重复的,则必相邻,相当于找重复的那步从 n*n,简化到 nlogn.

但是,在这个过程中,需要知道原来字符串的样子,所以,使用了额外空间。 

class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        vector<string> ans;
        if(strs.size() == 0 || strs.size() == 1)
            return ans;
        //sort every string
        vector<string> str_copy = strs;
        for(int i = 0;i<strs.size();i++)
            sort(str_copy[i].begin(),str_copy[i].end());

        //sort the whole vector
        vector<string> str_copy_copy = str_copy;
        sort(str_copy_copy.begin(),str_copy_copy.end());
        
        for(int i = 1; i<strs.size();i++)
        {
            if(str_copy_copy[i] == str_copy_copy[i-1])
            {
                //find all strings equal to it, and record its original string
                for(int j = 0;j<str_copy.size();j++)
                {
                    if(str_copy_copy[i] == str_copy[j])
                        ans.push_back(strs[j]);
                }
            }
            //to avoid duplicated compare and search, skip the same ones
            while(i<strs.size())
                if(str_copy_copy[i] == str_copy_copy[i-1])
                    i++;
                else
                    break;
        }
        return ans;
        
    }
};
原文地址:https://www.cnblogs.com/qingcheng/p/3805528.html