5.程式碼對齊(UVA1593)
阿新 • • 發佈:2018-11-19
程式碼對齊(UVA1593)
題目簡單分析
題目的詳細內容可以在這個網站上看到,下面簡單說明一下題目要求。
[題意]
本題主要任務是對輸入的程式碼進行對齊,例如:
start: integer; // begins here
stop: integer; // ends here
s: string;
c: char; // temp
輸出結果應為:
start: integer; // begins here
stop: integer; // ends here
s: string;
c: char; // temp
這裡要求在對齊的前提下,程式碼儘量緊縮,相鄰詞之間空格越少越好(最小為一個空格)。
測試樣例的輸入最多為180個詞*1000行,每個詞最長為80個字元。
[思路]
1.由於每行的單詞個數不確定,因此這裡考慮用C++的vector<string>
來儲存每行切分後的單詞。
2.由於需要對每行的程式碼進行對齊,因此需要對所有行求第i個單詞的最大長度,小於該最大長度的單詞用空格不足即可。
程式碼
完整程式碼如下,C++版本為C++11,VScode的工程在github。程式碼如有bug,敬請指出。
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
vector<string> line[1005];//儲存每行的資料
int maxLen[200];//每列字串最大長度
int main(){
int col=0, row=0, nRow=0;
string oneline, onestr;
//拆分字串->line[1005]、計算每列最大長度->maxLen
while (getline(cin, oneline)){
col=0;
stringstream ss(oneline);
while(ss >> onestr){
maxLen[col]=max(maxLen[col], (int)onestr.size());
line[row].push_back(onestr);
col++;
}
row++;
}
nRow=row-1;row=col=0;
//輸出
while(row <= nRow){//按行輸出
col=0;
for(auto str=line[row].begin();;str++){
cout << *str;
if(str==line[row].end()-1) break;//每行最後一個string後不加空格
for(int i = 0; i < maxLen[col]-(*str).length()+1;i++)
cout << " ";
col++;
}
cout << "\n";
row++;
}
return 0;
}