The task is to find the longest word and its length in the string. I know the other way to solve this problem, but I want to try it this way.
The string is "abra cadabra fibra" (cadabra 7 is an answer).
Thank you.
using namespace std;
vector<int> spacesPosititons(string s){
vector<int> positions;
int pos = s.find(' ');
while(pos != string::npos){
positions.push_back(pos);
pos = s.find(' ',pos+1);
}
return positions;
}
int main(){
//freopen("input.txt","r",stdin);
string str,word;
getline(cin,str);
str = " " + str + " ";
int max = 0;
vector<int> temp = spaces(str);
vector<int> diff;
for(int i = 0; i < temp.size(); ++i){
diff.push_back(temp[i+1]-temp[i]);
}
for(int i = 0; i < diff.size(); ++i){
if(diff[i] > max){
max = diff[i];
}
}
for(int i = 0; i < temp.size(); ++i){
if(temp[i+1]-temp[i] == max){
word = str.substr(temp[i]+1,max-1);
}
}
cout << word << endl << word.size();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire