【华科考研机试题】最长&最短文本

题目

输入多行字符串,请按照原文本中的顺序输出其中最短和最长的字符串,如果最短和最长的字符串不止一个,请全部输出。

解题思路

1.输入所有字符串(有空格不另算字符串)。
2.将char*字符串转换成string型。
3.由于map是自动排好序的,所以begin和end可以取到最小的地址和最大的后一个地址。

map <int,list<string>>m;//构造map
m[s.length].push_back(s);//map插入
list l = m.begin()->second();//map取最短
l = (--end())->second();//map取最长

4.将最长和最短的list输出即可。

难点

  1. 输入包含空格的字符串用gets或者getline。
  2. char*字符串转换成string字符串直接用等号。

代码

#include <bits/stdc++.h>
using namespace std;
int main(){
    string s;
    char c[1100];
    map <int, list<string>> m;
    int num;
    while(gets(c)){
        s = c; // char*转换成string
        m[s.length()].push_back(s);
    }
    list <string> l;
    list <string>::iterator it;
    
    l = m.begin()->second;//最短
    for(it = l.begin();it != l.end(); ++it){
        cout << *it << endl;
    }
    
    l = (--m.end())->second;//最长
    for(it = l.begin();it != l.end(); ++it){
        cout << *it << endl;
    }
    return 0;
}
posted @ 2019-02-23 00:00  ninding  阅读(170)  评论(0编辑  收藏  举报