在C ++中使用字符串的一个遍历的第一个非重复字符
在本教程中,我们将学习如何在给定的字符串中查找第一个非重复字符。让我们来看一个例子。
输入-nhooo
输出-u
让我们看看解决问题的步骤。
初始化字符串。
初始化映射字符和数组,以存储字符串中字符的频率。
遍历字符串。
找到每个字符的频率并将其存储在映射中。
还要存储字符的索引。
遍历映射中的字符频率。
以频率1打印第一个字符。
示例
让我们看一下代码。
#include <bits/stdc++.h>
#include <map>
using namespace std;
void findDistinctCharacters(string random_string) {
   //初始化字符数
   map<char, int[2]> chars;
   //遍历字符串
   for (int i = 0; i < random_string.size(); ++i){
      chars[random_string[i]][0]++;
      chars[random_string[i]][1] = i;
   }
   int char_index = INT_MAX;
   //打印频率为1的第一个字符
   for (auto item: chars) {
      //检查频率
      if (item.second[0] == 1) {
         char_index = min(char_index, item.second[1]);
      }
   }
   //打印频率为1的第一个字符
   cout << random_string[char_index] << u;
}
int main() {
   findDistinctCharacters("nhooo");
   return 0;
}输出结果如果运行上面的代码,则将得到以下结果。
u
结论
如果您对本教程有任何疑问,请在评论部分中提及。
