题解 | #单词识别#
单词识别
https://www.nowcoder.com/practice/16f59b169d904f8898d70d81d4a140a0
#include <algorithm>//先把单词给分解出来 #include <functional>//转换大小写 #include<iostream>//放入map里面,有这个元素就次数+1,没有就插入 #include <map> #include <set> #include<string> #include <utility> #include<vector> using namespace std; class Solution { public: void findWords(string& s) { size_t firstpos = 0; size_t nullpos = s.find(' ', firstpos); int i = 0; vector<string> vectemp; while (nullpos != string::npos) { vectemp.push_back(s.substr(firstpos, nullpos - firstpos)); i++; firstpos = nullpos + 1; nullpos = s.find(' ', firstpos); } if (firstpos < s.size()) { if (s.back() == '.') { vectemp.push_back(s.substr(firstpos, s.size() - firstpos - 1)); } else { vectemp.push_back(s.substr(firstpos)); } i++; } map<string, int> settree; int j=0; for(j=0; j<i; j++){ for (char& temp : vectemp[j]) { if (temp >= 'A' && temp <= 'Z') { temp += 32; } } auto it = settree.find(vectemp[j]); if(it != settree.end()){ (it->second)++; } else{ settree.insert(make_pair(vectemp[j], 1)); } } for (const auto& entry : settree) { cout << entry.first << ":" << entry.second << endl; } } }; int main(){ Solution solution; string input = "A blockhouse is a small castle that has four openings through which to shoot."; solution.findWords(input); return 0; }