How to find the most repeated character in a string with TypeScript

2 Answers

0 votes
function getMostRepeatedChar(str: string) { 
    // Create an object to store character frequencies
    const charCount = {};
    

    // Iterate through the string and count each character
    for (let char of str) {
        charCount[char] = (charCount[char] || 0) + 1;
    }

    // Find the character with the highest frequency
    let maxChar: string = '';
    let maxCount: number = 0;
    for (let char in charCount) {
        if (charCount[char] > maxCount) {
            maxChar = char;
            maxCount = charCount[char];
        }
    }

    return maxChar;
} 
 
const s: string = "c++typescriptcphpc#";
    
console.log(getMostRepeatedChar(s));
 
   
   
/*
run:
   
"c" 
   
*/

 



answered Nov 30, 2024 by avibootz
0 votes
function getMostRepeatedChar(s: string) { 
  let count: any = new Array(256); // 256 = ASCII table size
  const len: number = s.length;
       
  for (let i: number = 0; i < len; i++) 
       count[s[i]]++; 
     
  let max: any = count[s[0]];  
  let ch: string = s[0];
  for (let i: number = 1; i < len; i++) { 
       if (max < count[s[i]]) { 
           max = count[s[i]]; 
           ch = s[i]; 
       } 
  } 

  return ch; 
} 
 
const s: string = "c++typescriptcphpc#";
    
console.log(getMostRepeatedChar(s));
 
   
   
/*
run:
   
"c"
   
*/

 



answered Nov 30, 2024 by avibootz
...