我是Hacker Rank的一个简单问题。
有N个字符串。每个字符串的长度不超过20个字符。还有Q查询。对于每个查询,您将获得一个字符串,您需要找出此字符串之前发生的次数。第一行包含字符串数。接下来的N行每行包含一个字符串。 N +第2行包含查询数。 以下Q行每个都包含一个查询字符串。
示例输入
4
aba
baba
aba
xzxb
3
aba
xzxb
ab
示例输出
2
1
0
这是提供的代码,
function processData(input) {
//Enter your code here
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
问题的解决方案很简单。 初始化哈希映射。在hashmap中输入N个字符串中的值,以防止出现计数。
var map = {};
if(!map[input])map[input]++;
else map[input] = 1;
然后为每个查询返回相应键的get。
问题是我是javascript的新手并且对节点没有任何线索。有人可以帮助我理解代码并帮助我弄清楚各个数据结构必须实例化的范围。
答案 0 :(得分:0)
您需要将代码放入:
function processData(input) {
// split your input and access it
//your logic
var map = {};
if(!map[input])map[input]=1;
else map[input] +=1;
//your output
console.log('...');
}
<强>释强>
从stdin开始读取所以我们不退出。
process.stdin.resume();
读取输入数据
process.stdin.on("data", function (input) {
_input += input;
});
完成数据调用后会触发结束事件。
process.stdin.on("end", function () {
processData(_input);
});