以出現的順序列印奇數頻率的字元


在此問題中,使用者給了我們字串 str。我們只需要列印僅出現次數為奇數的字元。

要解決此問題,我們必須計算一個字元在字串中的出現總次數。並且僅打印出現次數為奇數的字串字元。

我們舉一個例子,以便更好地理解這個主題 −

Input : adatesaas.
Output : dte

說明 −帶有其出現頻率的字元為 −

a4
d1
t1
e1
s2

出現次數為奇數的字元是 d、t、e。

演算法

現在我們嘗試建立一個演算法來解決此問題 −

Step 1 : Traverse the string and count the number of occurrences on characters of the string in an array.
Step 2 : Traverse the frequency array and print only those characters whose frequency of occurrence is odd.

示例

我們基於此演算法建立一個程式 −

 線上示例

#include <bits/stdc++.h>
using namespace std;
int main(){
   string str = "asdhfjdedsa";
   int n = str.length();
   int frequency[26];
   memset(frequency, 0, sizeof(frequency));
   for (int i = 0; i < n; i++)
      frequency[str[i] - 'a']++;
   for (int i = 0; i < n; i++) {
      if (frequency[str[i] - 'a'] % 2 == 1) {
         cout << str[i]<<" , ";
      }
   }
   return 0;
}

輸出

d , h , f , j , d , e , d

更新於: 03-Jan-2020

379 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.