试题 算法提高 统计单词数
<span style="color:#344659"><span style="color:#666666">This is a test. This test is easy. This is a test. This test is easy.</span></span>
样例输出
THIS:****4 IS:****4 A:**2 TEST:****4 EASY:**2
解题思路:模拟。吐槽一下:最后的输出格式,真是搞脑经,什么“最长的单词顶格输出,它前面没有多余的空格; 其余单词与其右对齐”,最后,还是靠我对照评测数据的每个单词前面的空格数,找出规律,给算了出来(非最长单词输出时为了保证所谓的“其余单词与其右对齐”,它们的前面得输出空格,而空格数=ceil(double(maxL-len)/2 ),其中maxL 是最长单词的长度,Len是当前单词的长度 )。
AC代码如下:
#include <iostream>
#include <string.h>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
using namespace std;
vector<string> words;
map<string,int> G;
int maxL=0;
string ToUpper(string st){
int len=st.size();
for(int i=0;i<len;i++){
st[i]=toupper(st[i]);
}
return st;
}
void findAndSet(string st){
st=ToUpper(st);
int cnt=0;
for(int i=0;i<words.size();i++){
string curWord=words[i];
curWord=ToUpper(curWord);
if(curWord==st)
cnt++;
}
int bs=maxL-st.size();
bs=ceil(1.0*bs/2);
for(int i=0;i<bs;i++){
cout<<" ";
}
cout<<st<<":";
for(int i=1;i<=cnt;i++){
cout<<"*";
}
cout<<cnt<<endl;
G[st]=cnt;
}
void getTimes(){
for(int i=0;i<words.size();i++){
string cur=words[i];
cur=ToUpper(cur);
if(!G[cur])
findAndSet(cur);
}
}
int main(int argc, char** argv) {
string word;
while(cin>>word)
{
int len=word.size();
if(word[len-1]<'A' || word[len-1]>'z'){
words.push_back(word.substr(0,len-1));
len--;
}
else
words.push_back(word);
maxL=max(maxL,len);
char c=cin.get();
if(c=='\n')
{
break;
}
}
getTimes();
return 0;
}