更改字符串的性别,即切换输入字符串中所有性别特定的单词。 例如:
null
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<bits/stdc++.h> 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 <string, string> 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是输入字符串的长度。
改进范围:
- 我们可以在字典中添加更多单词及其对应词,以提高程序的准确性。例如,我们可以在字典中添加–“演员、女演员”、“上帝、女神”。
- 还可以导入所有女性和男性单词的文本文件。
- 该程序可以修改为不区分大小写。
本文由 拉希特·贝尔瓦里亚 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END