77. 翻转单词顺序
讲解视频:https://www.acwing.com/video/2728/
单词反转函数
string reverseWords(string s)
{reverse(s.begin(), s.end());for (int i = 0; i < s.size(); i++){int j = i + 1;while (j < s.size() && s[j] != ' ') j++;reverse(s.begin() + i, s.begin() + j);i = j;}return s;
}
完整C++代码:
class Solution
{
public:string reverseWords(string s){reverse(s.begin(), s.end());for (int i = 0; i < s.size(); i++){int j = i + 1;while (j < s.size() && s[j] != ' ') j++;reverse(s.begin() + i, s.begin() + j);i = j;}return s;}
};
3581. 单词识别
讲解视频:https://www.acwing.com/video/5473/
#include <cstring>
#include <iostream>
#include <map>using namespace std;string s;
map<string, int> h;int main()
{ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);getline(cin, s);for (int i = 0; i < s.size(); i++){if (isalpha(s[i])) // 是字母{string word = "";int j = i;while (j < s.size() && isalpha(s[j])){word += tolower(s[j]);j++;}h[word]++;i = j;}}for (auto &[k, v] : h) cout << k << ":" << v << '\n';// for (auto &[k, v] : h) printf("%s:%d\n", k.c_str(), v);// 也可以用printf输出,就是要把string用c_str函数转为字符数组return 0;
}