子串计算 -- map的用法

描述

题目描述
给出一个01字符串(长度不超过100),求其每一个子串出现的次数。
输入描述:
输入包含多行,每行一个字符串。
输出描述:
对每个字符串,输出它所有出现次数在1次以上的子串和这个子串出现的次数,输出按字典序排序。
示例1

输入
10101
输出
0 2
01 2
1 3
10 2
101 2

分析

确实是需要一小段一小段来查
考虑两个问题:如何查找子串;如何保证不遗漏子串;要最后保证字典序排序
map 可以用string做键;用find查找有无string;用值表示次数;本身是字典序
不遗漏子串,就从第一个字母开始遍历,每次从当前位置依次往后加一个,就是正常的计数所有可能子串的思路

代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<map>
#include<string>
using namespace std;
map<string, int>com;
map<string, int>::iterator it;
int main()
{
    string input;
    while (cin>>input)
    {
        int len = input.length();
        string c="";
        com.clear();
        for (int i = 0; i < len; i++)
        {
            c = "";
            c += input[i];
            if (com.find(c) != com.end())
                com[c]++;
            else
                com[c] = 1;
            for (int j = i + 1; j < len; j++)
            {
                c += input[j];
                if (com.find(c) != com.end())
                    com[c]++;
                else
                {
                    com[c] = 1;
                }
            }
        }

        for (it = com.begin(); it != com.end(); it++)
        {
            if ((*it).second > 1)
                cout << (*it).first << " " << (*it).second << "\n";
        }
    }
}

收获

有段时间不用map了,但其实挺好用的
map < string,int>mapp;
第一个是key,第二个是value, key按顺序的,不重复;可以直接用中括号索引key得到value
可以根据key值快速查找


插入:
mapStudent.insert(pair< int, string>(1, “student_one”)); 或者直接
mapStudent[1] = “student_one”;
第一种插入在有key值时不会插入,第二种会覆盖原来的值
map.size()返回当前插入了多少数据


遍历
map< string,int>::iterator it;
for(it = mapp.begin();it!=mapp.end();it++)
(*it).first —-key (*it).second —value;
或者
for(int i = 0;i< mapp.size();i++)
mapp[i]访问int键的值;具体for循环的开始结束取决于int键值,一般不用


查找
mapp.count(key)判断有没有,要么1要么0
mapp.find()返回的是数据所在位置迭代器,只要!=mapp.end()就是找到了


mapp.clear()清空map
mapp.empty()是否为空

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值