【问题标题】:Removing the most frequent character from a string - C++从字符串中删除最常见的字符 - C++
【发布时间】:2016-11-10 01:06:45
【问题描述】:

标题说明了一切 - 我的字符串只能由空格分隔的数字组成,例如1 0 3 0 4 0 7 0。我想要做的是删除最常出现的字符,然后得到 1 3 4 7。总会有一个数字重复。我试过了,但它只删除了重复项,而不是字符的实际出现:

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

我也尝试过逐个字符循环遍历字符串,然后删除最常出现但不起作用的字符串:

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());
                }
        }
}

任何帮助将不胜感激! :)

【问题讨论】:

    标签: string character


    【解决方案1】:

    试试这个代码

    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";
    }
    

    【讨论】:

      【解决方案2】:

      在你声明你的字符串之后:

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

      您可以使用替换语句(如果您愿意,可以使用可以为您找到最常见情况的函数)

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

      如果您想使用一个函数来告诉您哪个字符最常见,那么您可以将其放入替换函数的第一个参数中。

      如果这有帮助,请告诉我!

      【讨论】:

      • 感谢您的快速回复!我实际上想通了——我实现了我的函数来查找最常出现的字符,但现在我遇到了另一个问题:我忘了提到我的行可能是这样的:
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2011-01-19
      • 2022-01-09
      • 2011-12-10
      相关资源
      最近更新 更多