Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- const fs = require('fs');
- process.stdin.resume();
- process.stdin.setEncoding('utf-8');
- let inputString = '';
- let currentLine = 0;
- process.stdin.on('data', inputStdin => {
- inputString += inputStdin;
- });
- process.stdin.on('end', _ => {
- inputString = inputString.replace(/\s*$/, '')
- .split('\n')
- .map(str => str.replace(/\s*$/, ''));
- main();
- });
- function readLine() {
- return inputString[currentLine++];
- }
- // Solution start
- function getColorFreq(bugs) { // :Object{color:count, ...}
- return bugs.split("").reduce(
- (a, b) => {
- a[b] = (a[b] | 0) + 1;
- return a;
- }, {}
- );
- }
- function onlySpaces(bugs) { // :Boolean
- return bugs.match(/^_+$/g) != null;
- }
- function alreadyHappy(bugs) { // :Boolean
- if (onlySpaces(bugs)) return true;
- const len = bugs.length;
- if (len < 2 ||
- bugs[0] !== bugs[1] ||
- bugs[len - 1] !== bugs[len - 2]) return false;
- for (let i = 1; i < len - 2; ++i) {
- if (
- bugs[i] !== "_" &&
- bugs[i] !== bugs[i - 1] &&
- bugs[i] !== bugs[i + 1]
- ) return false;
- }
- return true;
- }
- function canBeHappy(bugs) { // :Boolean
- const freq = getColorFreq(bugs);
- for (const color in freq) {
- if (color !== '_' && freq[color] < 2)
- return false;
- }
- return freq['_'] > 0;
- }
- // Complete the happyLadybugs function below.
- function happyLadybugs(bugs) {
- return alreadyHappy(bugs) || canBeHappy(bugs) ? "YES" : "NO";
- }
- function tests() {
- console.assert(onlySpaces("_") === true);
- console.assert(onlySpaces("_____") === true);
- console.assert(onlySpaces("_____") === true);
- console.assert(onlySpaces("A____") === false);
- console.assert(onlySpaces("__A__") === false);
- console.assert(onlySpaces("____A") === false);
- const freq = getColorFreq("ABCD_BCD_CD_D");
- console.assert(freq['A'] === 1);
- console.assert(freq['B'] === 2);
- console.assert(freq['C'] === 3);
- console.assert(freq['D'] === 4);
- console.assert(freq['_'] === 3);
- console.assert(alreadyHappy("BBCCAA") === true);
- console.assert(alreadyHappy("BB") === true);
- console.assert(alreadyHappy("BBCC_AA") === true);
- console.assert(alreadyHappy("A") === false);
- console.assert(alreadyHappy("BBC_CAA") === false);
- console.assert(alreadyHappy("BCCAAB") === false);
- console.assert(alreadyHappy("BCC_AAB") === false);
- }
- function main() {
- tests();
- const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
- const g = parseInt(readLine(), 10);
- for (let gItr = 0; gItr < g; gItr++) {
- const n = parseInt(readLine(), 10);
- const b = readLine();
- let result = happyLadybugs(b);
- ws.write(result + "\n");
- }
- ws.end();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement