在給定的 C++ 字串陣列中列印全部成對出現的三元組
在本題目中,給定一個字串陣列,我們要打印出全部成對的三元組。
三元組是指透過重排字串中的字元形成的字串。譬如:hello 和 lolhe
我們透過一個例子來了解題目——
Input: array = {“hello”, “hrdef”, “from”, “lohel”, “morf”}.
Output: [hello, lohel] , [from , morf]要解決此問題,我們將使用巢狀迴圈。我們需要兩個巢狀迴圈,外部迴圈將遍歷陣列並選擇元素。巢狀迴圈將檢查每個字串並檢視它們是否是三元組。
示例
下面是實現這一演算法的程式——
#include <iostream>
using namespace std;
#define NO_OF_CHARS 256
bool isAnagramString(string str1, string str2){
int count[NO_OF_CHARS] = {0};
int i;
for (i = 0; str1[i] && str2[i]; i++){
count[str1[i]]++;
count[str2[i]]--;
}
if (str1[i] || str2[i])
return false;
for (i = 0; i < NO_OF_CHARS; i++)
if (count[i])
return false;
return true;
}
void printAnagrams(string arr[], int n){
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++)
if (isAnagramString(arr[i], arr[j]))
cout<<arr[i]<<" and "<<arr[j]<<" are anagrams.\n";
}
int main(){
string arr[] = {"hello", "hrdef", "from", "lohel", "morf"};
int n = sizeof(arr)/sizeof(arr[0]);
printAnagrams(arr, n);
return 0;
}輸出
hello and lohel are anagrams. from and morf are anagrams.
此解決方案非常易於理解,但效率較低。因此,我們可以對解決方案進行一些最佳化,使其更有效。我們可以透過對包含字串的陣列排序來實現。透過排序陣列,可以更輕鬆地找到三元組。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP