AcWing 774. 最长单词
原题链接
中等
作者:
Backkom
,
2021-03-28 14:41:23
,
所有人可见
,
阅读 264
解法1 借鉴770题的做法 用stringstream ssin
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string str, r, s;
getline(cin, str);
stringstream ssin(str.substr(0, str.size() - 1));
int cnt = 0 , max = 0;
while(ssin >> r)
{
if (r.size() > max) max = r.size(), s = r;
}
cout << s << endl;
return 0;
}
解法2 双指针
#include <iostream>
using namespace std;
int main()
{
string str, r;
getline(cin, str);
int l = str.size() - 1, cnt = 0;
for(int i = 0; i < l; i ++)
{
int j = i;
while(j < l && str[j] != ' ') j ++;
if(str[i] == ' ') continue;
if(j - i > cnt) cnt = j - i, r = str.substr(i, cnt);
i = j - 1;
}
cout << r << endl;
return 0;
}