C++程式:將給定字串重新排序以形成K個連線的字串


給定一個字串和一個整數 k,我們需要重新排列字串中的字元,使其成為 k 個相似子字串的連線。如果不可能,則輸出結果為“Impossible”。

string = "malaalam";
K = 2;
res = solve(s, K);

示例(使用對映)

假設我們有一個字串“mottom”和 K=2。給定字串可以表示為 2 個子字串的連線,例如 tomtom、motmot、omtomt 等。在所有這 3 個示例中,當 k = 2 時,兩個子字串連線在一起。

使用字串,我們可以確定每個字元出現的次數。然後,如果所有可用的頻率都可被 k 整除,則它是可能的,我們可以輸出任何可能的答案。否則,這是不可能的。

上述示例的 C++ 實現如下:

#include <iostream> #include <map> using namespace std; string solve(string s, int k) { map<char, int> mp; for (char ch : s) { mp[ch]++; } string repeatedSubstring = ""; for (auto &val : mp) { if ((val.second % k) != 0) { return "Impossible"; } else { for (int i=0;i<val.second/k;i++) { repeatedSubstring+=val.first; } } } string ans = ""; for (int i = 0; i < k; i++) { ans+= repeatedSubstring; } return ans; } int main() { string s = "mottom"; int K = 2; cout << solve(s, K); return 0; }

輸出

motmot

示例(不使用對映)

不使用對映的相同示例的 C++ 實現如下:

#include <bits/stdc++.h> using namespace std; int main() { string str = "mottom"; int k = 2; int frqncy[26] = { 0 }; int len = str.length(); for (int i = 0; i < len; i++) { frqncy[str[i] - 'a']++; } string single_copy = ""; for (int i = 0; i < 26; i++) { if (frqncy[i] != 0) { if ((frqncy[i] % k) != 0) { string ans = "Not Possible"; cout << ans; } else { int total_occurrences = (frqncy[i] / k); for (int j = 0; j < total_occurrences; j++) { single_copy += char(i + 97); } } } } string kString; for (int i = 0; i < k; i++) { kString += single_copy; } cout << kString; return 0; }

輸出

motmot

結論

我們可以使用 map 或 unordered_map 將字元對映到頻率。我們可以使用 [26] 的陣列表示拉丁小寫字元,並將所有 freq 設定為 0。這是一個基於實現的問題,使用 unordered_map 或 hashmap 的時間複雜度為 O(n)。

更新於: 2022年8月10日

102 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告