注意整行输入的格式
#include<iostream> #include<sstream> using namespace std; string reorderSpaces(string text) { string words[55]; int n = text.size(),cntWords = 0, lo = 0, hi = 0,cntSpace = 0,avgSpace = 0,tailSpace = 0; while (lo < n) { while (lo < n && text[lo] == ' ') { cntSpace++; lo++; } hi = lo; while (hi < n && text[hi] != ' ') { hi++; } if (lo != hi) { words[cntWords++] = text.substr(lo, hi - lo); } lo = hi; } if (cntWords == 1) { text = words[0]; for (int i = 0; i < cntSpace; i++) { text += " "; } } else { avgSpace = cntSpace / (cntWords-1); tailSpace = cntSpace % (cntWords-1); text = ""; for (int i = 0; i < cntWords-1; i++) { text += words[i]; for (int j = 0; j < avgSpace; j++) { text += " "; } } text += words[cntWords - 1]; for (int i = 0; i < tailSpace; i++) { text += " "; } } return text; } int main() { string s; while (getline(cin,s) ){ cout<<reorderSpaces(s)<<endl; } return 0; }
标签:++,lo,1592,int,hi,cntWords,text,leetcode From: https://www.cnblogs.com/stevenzrx/p/17237379.html