Skip to content

Commit 83cc09c

Browse files
committed
sherlock-and-anagrams
1 parent 8ca9f19 commit 83cc09c

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

sherlock-and-anagrams.js

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
'use strict';
2+
3+
const fs = require('fs');
4+
5+
process.stdin.resume();
6+
process.stdin.setEncoding('utf-8');
7+
8+
let inputString = '';
9+
let currentLine = 0;
10+
11+
process.stdin.on('data', inputStdin => {
12+
inputString += inputStdin;
13+
});
14+
15+
process.stdin.on('end', _ => {
16+
inputString = inputString.replace(/\s*$/, '')
17+
.split('\n')
18+
.map(str => str.replace(/\s*$/, ''));
19+
20+
main();
21+
});
22+
23+
function readLine() {
24+
return inputString[currentLine++];
25+
}
26+
27+
function sherlockAndAnagrams(s) {
28+
let hash = {};
29+
for (let i = 0; i < s.length; i++) {
30+
for (let j = i + 1; j < s.length + 1; j++) {
31+
let key = s.slice(i, j).split('').sort().join('');
32+
hash[key] = hash[key] ? hash[key] + 1 : 1;
33+
}
34+
35+
}
36+
let count = 0;
37+
for (let key in hash) {
38+
if (key !== s) {
39+
// n * n-1 /2
40+
count += hash[key] * (hash[key] - 1) / 2;
41+
};
42+
}
43+
return count;
44+
45+
}
46+
47+
function main() {
48+
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
49+
50+
const q = parseInt(readLine(), 10);
51+
52+
for (let qItr = 0; qItr < q; qItr++) {
53+
const s = readLine();
54+
55+
let result = sherlockAndAnagrams(s);
56+
57+
ws.write(result + "\n");
58+
}
59+
60+
ws.end();
61+
}

0 commit comments

Comments
 (0)