Special String Again

  • + 0 comments

    import { WriteStream, createWriteStream } from 'fs'; import { stdin, stdout } from 'process';

    // Function to count special substrings function substrCount(n: number, s: string): number { let count = 0;

    // Count all uniform substrings
    let i = 0;
    while (i < n) {
        let length = 1;
        while (i + 1 < n && s[i] === s[i + 1]) {
            length++;
            i++;
        }
        count += (length * (length + 1)) / 2;
        i++;
    }
    
    // Count all substrings of the form where one character is different in the middle
    for (let i = 1; i < n - 1; i++) {
        let length = 0;
        while (i - length >= 0 && i + length < n && s[i - length] === s[i + length] && s[i - length] !== s[i]) {
            count++;
            length++;
        }
    }
    
    return count;
    

    }

    // Main function to handle input and output function main() { const inputLines: string[] = [];

    stdin.setEncoding('utf-8');
    stdin.on('data', (chunk: string) => {
        inputLines.push(...chunk.trim().split('\n'));
    });
    
    stdin.on('end', () => {
        const outputStream: WriteStream = createWriteStream(process.env['OUTPUT_PATH'] || '/dev/stdout');
    
        const n: number = parseInt(inputLines[0].trim(), 10);
        const s: string = inputLines[1].trim();
    
        const result: number = substrCount(n, s);
    
        outputStream.write(result + '\n');
        outputStream.end();
    });
    

    }

    main();