• + 0 comments

    My answer in Typescipt, simple, not minimized

    function alternate(s: string): number {
        // get a set of character in [s]
        let chars: string[] = Array.from(new Set<string>(s.split('')))
    
        // get everys pair of 2 character in [s]
        let pairs: [string, string, string?, number?][] = []
        for (let i = 0; i < chars.length; i++) {
            for (let j = i + 1; j < chars.length; j++) {
                pairs.push([chars[i], chars[j]])
            }
        }
    
        // check each pair, save info after remove other character except character in that pair
        for (let i = 0; i < pairs.length; i++) {
            let pair = pairs[i]
            let astr = s.split('').filter(c => pair.includes(c))
    
            pair.push(astr.join(''))
            pair.push(astr.every((c, j) => c != astr[j + 1]) ? astr.length : 0)
        }
    
        console.log(pairs)
    
        // return the largest valid result in [pairs]
        return Math.max(0, ...pairs.map(([a, b, str, result]) => result))
    }