'lintcode 反向索引'

描述

创建给定文档的反向索引

确保数据不包含标点符号.

样例

出一个包括id与内容的文档list(我们提供了document类).
返回一个反向索引(hashmap的key是单词, value是文档的id).

例 1:

输入:
[
{
“id”: 1,
“content”: “This is the content of document 1 it is very short”
},
{
“id”: 2,
“content”: “This is the content of document 2 it is very long bilabial bilabial heheh hahaha …”
},
]
输出:
{
“This”: [1, 2],
“is”: [1, 2],

}
例 2:

输入:
[
{
“id”: 1,
“content”: “you are young”
},
{
“id”: 2,
“content”: “you are handsome”
},
]
输出:
{
“are”: [1, 2],

}

思路

遍历每个content的每个字符串,插入到map中,并且更新map的vector,最后删除数组中的重复元素。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition of Document:
* class Document {
* public:
* int id;
* string content;
* }
*/
class Solution {
public:
/**
* @param docs a list of documents
* @return an inverted index
*/
map<string, vector<int>> invertedIndex(vector<Document>& docs) {
// Write your code here
stringstream ss;
map<string, vector<int>> m;
for (int i = 0; i < docs.size(); i++) {
int m_id = docs[i].id;
ss << docs[i].content;
for (string str; ss >> str; m[str].push_back(m_id));
ss.clear();
}
for (map<string, vector<int>>::iterator it = m.begin(); it != m.end(); it++) {
it->second.erase(unique(it->second.begin(), it->second.end()), it->second.end());
}
return m;
}
};
-------------end of file thanks for reading-------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值