We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Here is an approch for typescript using regex.
A bit longer due to comments and variable names.
functionalternate(s:string):number{// Write your code here// get unique chars in input stringconstavailableChars=Array.from(newSet<string>(s.split('')));// build available pair optionsconstavailablePairs:[string,string][]=[];availableChars.forEach((firstChar)=>{availableChars.forEach((secondChar)=>{if(firstChar===secondChar){// same, not an optionreturn;}// add pair combonation to list of available pairsavailablePairs.push([firstChar,secondChar]);});});// build array of lenths for each available pairconstpairsStrLenValues:number[]=availablePairs.map(([a,b]):number=>{// regex to find char that are not the current pairconstfindUnavailableCharsRegex=newRegExp(`[^${a}${b}]`,'gi');// regex to find duplicates of char a in stringconstfindDuplicateACharRegex=newRegExp(`[${a}]{2}`);// regex to find duplicates of char b in stringconstfindDuplicateBCharRegex=newRegExp(`[${b}]{2}`);// remove all char that are not in the current pair// @ts-ignore (due to lib version)constcleanedString=s.replaceAll(findUnavailableCharsRegex,``);// check for duplicates of char a and char b to check if cleaned string is validconstdoesCleanStringHaveDuplicateAChar=!!findDuplicateACharRegex.exec(cleanedString);constdoesCleanStringHaveDuplicateBChar=!!findDuplicateBCharRegex.exec(cleanedString);constisCleanedStringValid:boolean=(!doesCleanStringHaveDuplicateAChar&&!doesCleanStringHaveDuplicateBChar);if(!isCleanedStringValid){// cleaned string not valid so return length of zeroreturn0;}// return length of valid stringreturncleanedString.length;});returnMath.max(0,...pairsStrLenValues);}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Two Characters
You are viewing a single comment's thread. Return to all comments →
Here is an approch for typescript using regex. A bit longer due to comments and variable names.