【刘汝佳书】例题5-4 UVA156 (map的练习)

【2019.4.3】
这道题……大意了……

1、需要注意的地方:
输出按ASCII码序:大小写敏感!!!
也就是说:N要排在a前面,因为大写字母比小写字母的ascii码小

2、遇到的错误:Runtime error
第一次submit遇到了Runtime error,明明uDebug都过了emmm
第一次遇到Runtime error,查了下资料发现有以下几种情况:

C++ Runtime error的可能性
运行时错误大概分为以下几类:
1、访问到不应访问的地址(如数组越界)
2、内存溢出(如数组过大)
3、算术上溢或下溢(如除以0)
4、段错误(各种其它错误)

代码里没有用到数组、没有除法、估计没有段错误,应该就是内存溢出了

原来的数据结构用的是map<string, struct node*>,node里有string和bool类型,虽然测试了三千个单词没错,但可能oj里的测例有更大的数据吧

后来把数据结构改成了map<string, bool>,就过了

3、本题所用的数据结构
map<string, bool>:string存【原始输入的字符串s】,bool存【字符串s是否应该输出】

4、关键子函数
toLowerSort(string s,int length):把输入的字符串s,全都转换成小写,再把其中字母排序,返回新字符串ss

5、main流程:
每输入一个字符串s,遍历一遍map,判断toLowerSort(map的关键字)和toLowerSort(s)是否相同
如果存在相同的,证明这个字符串重复了,不应该输出
如果不存在相同的,证明这个字符串是第一次出现,插入map

#include <iostream>
#include <map>
#include <string>
#include <cctype>
#include <algorithm>

using namespace std;

string toLowerSort(string s, int length)
{
    string ss = "";
    for(int i=0; i<length; i++)
        ss+=tolower(s[i]);
    sort(ss.begin(), ss.end());
    return ss;
}

int main()
{
    //freopen("C:\\Users\\Summer\\Desktop\\input.txt", "r", stdin);
    //freopen("C:\\Users\\Summer\\Desktop\\output.txt", "w", stdout);

    map<string, bool> m;
    map<string, bool>::iterator it;

    string s;
    string ss;
    bool flag;

    while(cin>>s && s[0]!='#') {
        ss = toLowerSort(s, s.length());

        //cout<<ls<<endl;
        flag = true;	//字符串s是否重复
        for(it = m.begin(); it != m.end(); it++) {
        	//如果重复,就标记flag=false,并退出map的遍历
            if(toLowerSort(it->first, (it->first).length()) == ss) {
                it->second = false;
                flag = false;
                break;
            }
        }
        //如果不重复,就插入map
        if(flag) {
            m[s] = true;
        }
    }

	//输出
    for(it = m.begin(); it != m.end(); it++) {
        if(it->second)
            cout<<(it->first)<<endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41727666/article/details/89004317