簡體   English   中英

給定一個字符串,我如何僅將另一個字符串中的唯一字符添加到其中?

[英]Given a string, how can I add only unique characters from another string to it?

我已經嘗試了好幾個小時了,我嘗試使用std :: unique,但是結果很時髦,然后嘗試使用string :: find 我覺得如果我使用std :: vector會很容易做到這一點,我正在尋找一種使用標准庫實現此目的的有效方法,盡管我在此處和cpluplus.com上閱讀了許多有關此主題的問題,但是我不能用他們的答案來實現我所需要的。 如果這很簡單,我深表歉意,但現在我已經厭倦了嘗試其他事情。

例如:

int main(){

  std::string unique_chars;
  std::string new_string = "ABC"

  getUniqueChars(unique_chars, new_string);
  cout << unique_chars << endl;

  new_string = "ABDF"
  getUniqueChars(unique_chars, new_string);

  cout << unique_chars; 

  return 0;
}  

void getUniqueChars(string &unique_chars, string &new_string){

   //add only unique characters from new_string to unique_chars

   return;
}

應該輸出:

ABC
ABCDF

您可以使用std::set來實現。 將兩個字符串中的所有字符添加到集合中,然后從集合中創建一個新字符串。

// Create a set of characters from `unique_str`
std::set<char> set(unique_chars.begin(), unique_chars.end());

// Insert the characters from `new_string`
set.insert(new_string.begin(), new_string.end());

// The set now contains only unique characters from both strings, no duplicates
// Convert back to a string
unique_chars = std::string(set.begin(), set.end());

如果您具有支持C ++ 11的編譯器和標准庫,並且不希望對結果進行排序,則可以改用std::unordered_set

這是一個指導。 你必須做這份工作

  1. 然后連接兩個字符串
  2. 刪除重復項

這是刪除重復項的方法

std::sort(str.begin(), str.end()); str.erase(std::unique(str.begin(), str.end()), str.end());

我想一種方法是:

Algorithm:

取原始字符串,並根據每個字符將其哈希到哈希表中。

從新字符串中獲取每個字符,並檢查是否已標記哈希表存儲桶。

如果未標記,則將其附加到原始字符串,否則拒絕它。

Code(not tested):

string orig, new ;
char arr[26]={initialise with all alphabets}

for(int i=0;i<orig.size();i++)
arr[new[i]] = x;

for(int i=0;i<new.size();i++)
if(arr[new[i]] != x)
orig += new[i];

復雜度(用於預處理)將為O(N),即與原始數組長度成線性關系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM