查找给定字符串中的所有非重复字符

问题描述:

所以我给了这个问题:查找给定字符串中的所有非重复字符

查找给定字符串中的所有非重复字符;

在做了一些Google搜索之后,很明显我发现找到第一个不重复的字符很常见。我发现了很多如何做的例子,但是我没有找到任何关于如何找到所有非重复字符而不是第一个的例子。

我的示例代码到目前为止是:

#include <iostream> 
#include <unordered_map> 

using namespace std; 

char findAllNonRepeating(const string& s) { 

    unordered_map<char, int> m; 

    for (unsigned i = 0; i < s.length(); ++i) { 
     char c = tolower(s[i]); 

     if (m.find(c) == m.end()) 
      m[c] = 1; 
     else 
      ++m[c]; 
    } 

    auto best = m.begin(); 

    for (auto it = m.begin(); it != m.end(); ++it) 
     if (it->second <= best->second) 
      best = it; 

    return (best->first); 
} 


int main() 
{ 
    cout << findAllNonRepeating("dontknowwhattochangetofindallnonrepeatingcharacters") << endl; 
} 

我不知道我需要更改或添加有此找到所有的非重复的字符。

k,f,p,s应该是该字符串中的非重复字符。

任何提示或想法,非常感谢!

+1

只需修改第二个循环来查找值为1的所有元素,是不是很明显? – Beta

+0

您希望确定哪些字符会出现一次(并返回一个字符串)或对它们进行计数,但计算出现的字符出现次数最少。 – molbdnilo

+0

这感觉就像一个家庭作业问题。 –

正如所建议的,只需保留一个频率图。然后,一旦字符串被处理,迭代地图,只返回那些恰好出现一次的值。

#include <iostream> 
#include <map> 
#include <vector> 

using namespace std; 

std::vector<char> nonRepeating(const std::string& s) 
{ 
    std::map<char, int> frequency; 
    for(int i=0;i<s.size();i++) 
    { 
     frequency[s[i]]++; 
    } 
    std::vector<char> out; 
    for(auto it = frequency.begin(); it != frequency.end(); it++) 
    { 
     if(it->second == 1) 
      out.push_back(it->first); 
    } 
    return out; 
} 

int main() { 
    // your code goes here 
    std::string str = "LoremIpsum"; 
    for(char c : nonRepeating(str)) 
    { 
     std::cout << c << std::endl; 
    } 
    return 0; 
} 
+0

谢谢Joris,我很感激帮助。在编码方面我还是很初学者!这帮了我很多。 – JFive575