重复字母连续出现次数

重复字母连续出现次数

 1process.stdin.resume();  2process.stdin.setEncoding('utf-8');  3let input = '';  4  5process.stdin.on('data', (data) => {  6 input += data;  7});  8  9process.stdin.on('end', () => { 10 // 去除字符串末尾可能存在的换行符或回车符 11 input = input.trim(); 12 13 // 检查输入字符串是否只包含大写字母且长度在1到100之间 14 if (!/^[A-Z]{1,100}$/.test(input)) { 15 console.error('输入字符串不符合要求。'); 16 process.exit(1); 17 } 18 19 // 实现计算同一字母连续出现最大次数的函数 20 function maxConsecutiveCharCount(str) { 21 let maxCount = 1; 22 let currentCount = 1; 23 24 for (let i = 1; i < str.length; i++) { 25 if (str[i] === str[i - 1]) { 26 currentCount++; 27 } else { 28 if (currentCount > maxCount) { 29 maxCount = currentCount; 30 } 31 currentCount = 1; 32 } 33 } 34 35 // 检查循环结束后最后一个字符序列的连续次数 36 if (currentCount > maxCount) { 37 maxCount = currentCount; 38 } 39 40 return maxCount; 41 } 42 43 // 调用函数并输出结果 44 const result = maxConsecutiveCharCount(input); 45 console.log(result); 46 47 process.exit(0); // 正常退出程序 48});
process.stdin.resume(); process.stdin.setEncoding('utf-8'); let input = ''; process.stdin.on('data', (data) => { input += data; }); process.stdin.on('end', () => { // 去除字符串末尾可能存在的换行符或回车符 input = input.trim(); // 检查输入字符串是否只包含大写字母且长度在1到100之间 if (!/^[A-Z]{1,100}$/.test(input)) { console.error('输入字符串不符合要求。'); process.exit(1); } // 实现计算同一字母连续出现最大次数的函数 function maxConsecutiveCharCount(str) { let maxCount = 1; let currentCount = 1; for (let i = 1; i < str.length; i++) { if (str[i] === str[i - 1]) { currentCount++; } else { if (currentCount > maxCount) { maxCount = currentCount; } currentCount = 1; } } // 检查循环结束后最后一个字符序列的连续次数 if (currentCount > maxCount) { maxCount = currentCount; } return maxCount; } // 调用函数并输出结果 const result = maxConsecutiveCharCount(input); console.log(result); process.exit(0); // 正常退出程序 });

Powered By 可尔物语

浙ICP备11005866号-12