華為機試HJ27-查找兄弟單詞-C++實現

HJ27 查找兄弟單詞

題目描述:

描述
    定義一個單詞的“兄弟單詞”為:交換該單詞字母順序(注:可以交換任意次),
    而不添加、刪除、修改原有的字母就能生成的單詞。
    兄弟單詞要求和原來的單詞不同。例如: ab 和 ba 是兄弟單詞。 ab 和 ab 則不是兄弟單詞。
    現在給定你 n 個單詞,另外再給你一個單詞 x ,讓你尋找 x 的兄弟單詞里,按字典序排列后的第 k 個單詞是什么?
    注意:字典中可能有重復單詞。

    數據范圍:1≤n≤1000 ,輸入的字符串長度滿足 1≤len(str)≤10  , 1≤k<n
    輸入描述:
    輸入只有一行。 先輸入字典中單詞的個數n,再輸入n個單詞作為字典單詞。 然后輸入一個單詞x 最后后輸入一個整數k
    輸出描述:
    第一行輸出查找到x的兄弟單詞的個數m 第二行輸出查找到的按照字典順序排序后的第k個兄弟單詞,沒有符合第k個的話則不用輸出。
    示例1
    輸入:
    3 abc bca cab abc 1
    輸出:
    2
    bca

    示例2
    輸入:
    6 cab ad abcd cba abc bca abc 1
    輸出:
    3
    bca
    說明:
    abc的兄弟單詞有cab cba bca,所以輸出3
    經字典序排列后,變為bca cab cba,所以第1個字典序兄弟單詞為bca

解題思路:

這是一道字符串的題目。
編寫一個用于判斷兩個單詞字符串s1, s2,如果s1和s2的長度不相同,或者s1和s2相等,則表示s1、s2不是兄弟;接著分別將s1和s2按照字典序進行排序,如果兩者相等則是兄弟單詞,否則不是。
具體的C++實現如下:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

bool isBotherWord(const string &source, const string &dest)
{
   // 注意:排除source == dest的情況
   if (source.length() != dest.length() || source == dest) {
       return false;
   }
   string s1 = source;
   std::sort(s1.begin(), s1.end());
   string s2 = dest;
   std::sort(s2.begin(), s2.end());
   return s1 == s2;
}

int main() {
   int n, k;
   vector<string> sVec;
   string x;
   while (cin >> n) { // 注意 while 處理多個 case
       // 輸入n個單詞作為字典單詞
       string sTemp;
       for (int i = 0; i < n; i++) {
           cin >> sTemp;
           sVec.push_back(sTemp);
       }
       cin >> x;
       cin >> k;
       vector<string> botherWords;
       for (auto word : sVec) {
           if (isBotherWord(x, word)) {
               botherWords.push_back(word);
           }
       }
       // 對botherWords按照字典順序進行排序
       std::sort(botherWords.begin(), botherWords.end());
       cout << botherWords.size() << endl;
       if ((int)(botherWords.size()) > 0 && k <= (int)(botherWords.size()) - 1) {
           cout << botherWords[k-1] << endl;
       }
       sVec.clear();
   }
}
// 64 位輸出請用 printf("%lld")
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容