2016-11-09 10 views
0

タイトルはそれをすべて言います - 文字列は空白で区切られた数字でのみ構成されます。 1 0 3 0 4 0 7 0.私がしたいのは、最も頻繁に出現する文字を削除してから1 3 4 7を得ることです。繰り返される数字は常に1つだけです。文字の実際の発生私はこれを試してみましたが、それは唯一の重複を削除し、ない:文字列から最も頻度の高い文字を削除する - C++

string newString = "1 0 3 0 4 0 7 0"; 
sort(newString.begin(), newString.end()); 
newString.erase(unique(newString.begin(), newString.end()), newString.end()); 

私も文字による文字列の文字をループしようとしましたが、その後、ほとんどが発生しているものを除去するが、それはdoesnのき働いている:

void countCharacters(const char n[], char count[]) 
{ 
int c = 0; 
while (n[c] != '\0') 
    { 
    if (n[c] >= '0' && n[c] <= '9') 
     count[n[c] - '0']++; 
    } 
} 

void myFunction() 
{ 
string newString = "1 0 3 0 4 0 7 0"; 
char count[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; 
const char *charString = newString.c_str(); 
countCharacters(charString, count); 
for (unsigned int z = 0; z < strlen(charString); z++) 
     { 
      if (count[z] > 1) 
       { 
       newString.erase(remove(newString.begin(), newString.end(), count[z]), newString.end()); 
       } 
     } 
} 

何か助けていただければ幸いです!あなたの文字列を宣言した後:)

答えて

0

すると、このコード

void solve() { 
string s = "1 0 3 0 4 0 7 0"; 
    int mx_count = 0, cnt[10] = {0}; 
    char mx_occ = '0'; 
    for(int i = 0; i < int(s.size()); i++) { 
    if('0' <= s[i] && s[i] <= '9') { 
     cnt[s[i] - '0']++; 
     if(cnt[s[i] - '0'] > mx_count) 
     mx_count = cnt[s[i] - '0'], mx_occ = s[i]; 
    } 
    } 
    queue<int> idxs; 
    for(int i = 0; i < int(s.size()); i++) { 
    if(!('0' <= s[i] && s[i] <= '9')) continue; 
    if(s[i] == mx_occ) idxs.push(i); 
    else { 
     if(!idxs.empty()) { 
     int j = idxs.front(); 
     idxs.pop(); 
     swap(s[i], s[j]); 
     idxs.push(i); 
     } 
    } 
    } 
    // instead of the below while loop 
    // you can loop on the queue and 
    // erase the chars at the positions in that queue. 

    int i = int(s.size()) - 1; 
    while(i >= 0 && (!('0' <= s[i] && s[i] <= '9') || s[i] == mx_occ)) { 
    --i; 
    } 
    if(i >= 0) s = s.substr(0, i + 1); 
    else s = ""; 
    cout << s << "\n"; 
} 
0

をお試しください:

string newString = "1 0 3 0 4 0 7 0"; 

あなたはあなたの場合はあなたのための最も一般的な発生を見つける機能を使用して(置き換えステートメントを使用することができます希望します)

newString = newString.replace(" 0", " "); 

機能を使用して、どの文字が最も一般的な場合、replace関数の最初の引数にその値を入れることができます。

これが役立つ場合はお知らせください。

+0

迅速な返信をありがとう!私は実際にそれを理解しました - 最も頻繁に発生する文字を見つけるために私の機能を実装しましたが、私は別の問題を抱えています:私の行は次のようになることを忘れていました: – JavaNewb

関連する問題