📜  更改给定字符串的性别

📅  最后修改于: 2022-05-13 01:57:07.719000             🧑  作者: Mango

更改给定字符串的性别

更改字符串的性别,即切换输入字符串中所有特定于性别的单词。
例子:

Input:  “she is my sister” 
Output:  “he is my brother”.
There are two gender-specific words in this
sentence:“she” and “sister”. After toggling
gender specific words to their respective 
counterparts - “he” and “brother” :
Gender specific words of the string are now 
changed.

算法:

  • 维护一个哈希图,将所有“女性”词映射到“男性”词,将所有“男性”词映射到“女性”词。
  • 然后对于字符串中的每个单词,我们检查这是否是一个特定于性别的单词。如果是,那么我们将这个词与它的对应词交换。否则我们不交换这个词。
  • 所有的单词都连接成一个新的字符串,最后打印出来,是我们需要的字符串。
// A C++ Program to change the gender of a string
#include
using namespace std;
  
// A Function that returns the new string with gender
// changed
string changeGender(string str)
{
    // A Dictionary to store the mapping of genders
    // The user can add his words too.
    unordered_multimap  dictionary =
    {
      {"batman", "batwoman"}, {"batwoman", "batman"},
      {"boy", "girl"}, {"girl", "boy"},
      {"boyfriend", "girlfriend"}, {"girlfriend", "boyfriend"},
      {"father", "mother"}, {"mother", "father"},
      {"husband", "wife"}, {"wife", "husband"},
      {"he", "she"}, {"she", "he"},
      {"his", "her"}, {"her", "his"},
      {"male", "female"}, {"female", "male"},
      {"man", "woman"}, {"woman", "man"},
      {"Mr", "Ms"}, {"Mr", "Ms"},
      {"sir", "madam"}, {"madam", "sir"},
      {"son", "daughter"}, {"daughter", "son"},
      {"uncle", "aunt"}, {"aunt", "uncle"},
    };
  
    str = str + ' '; // Append a space at the end
  
    int n = str.length();
  
    // 'temp' string will hold the intermediate words
    // and 'ans' string will be our result
    string temp = "", ans = "";
  
    for (int i=0; i<=n-1; i++)
    {
        if (str[i] != ' ')
            temp.push_back(str[i]);
        else
        {
            // If this is a 'male' or a 'female' word then
            // swap this with its counterpart
            if (dictionary.find(temp) != dictionary.end())
                temp = dictionary.find(temp)->second;
  
            ans = ans + temp + ' ';
            temp.clear();
        }
    }
  
    return(ans);
}
  
// Driver Program to test above functions
int main()
{
    string str = "she is going to watch movie with"
                " her boyfriend";
  
    cout << changeGender(str);
  
    return (0);
}

时间复杂度: O(N^2),其中 N 是字符串的长度,因为字符串的 '+'/'append'运算符字符串需要 O(N) 时间,并且假设在字典中查找需要 O( 1)更坏的情况时间。

辅助空间:除了将所有单词映射到对应词的字典外,我们为新字符串声明 O(N) 空间,其中 N 是输入字符串的长度。

改进范围:

  • 我们可以在字典中添加更多单词及其对应词,以提高程序的准确性。例如,我们可以在我们的字典中添加“演员、女演员”、“上帝、女神”。
  • 也可以导入所有女性和男性单词的文本文件。
  • 该程序可以修改为不区分大小写。