查找公共字符

查找公共字符

 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 let words = input.trim().split(' '); 11 12 /** 13 * 统计每个字符串的字符频率 14 */ 15 function countChars(str) { 16 let charCount = {}; 17 for (let char of str) { 18 charCount[char] = (charCount[char] || 0) + 1; 19 } 20 return charCount; 21 } 22 23 /** 24 * 找出所有字符串中的公共字符频率(取最小值) 25 */ 26 function findCommonChars(charCounts) { 27 let commonChars = charCounts[0]; 28 for (let i = 1; i < charCounts.length; i++) { 29 let current = charCounts[i]; 30 let tempCommon = {}; 31 for (let char in commonChars) { 32 if (current[char]) { 33 tempCommon[char] = Math.min(commonChars[char], current[char]); 34 } 35 } 36 commonChars = tempCommon; 37 } 38 return commonChars; 39 } 40 41 /** 42 * 根据字符频率构造结果字符串 43 */ 44 function constructResult(commonChars) { 45 let result = []; 46 for (let char in commonChars) { 47 result.push(char.repeat(commonChars[char])); 48 } 49 result.sort(); // 按字典序排序 50 return result.join(''); 51 } 52 53 // 主逻辑 54 let charCounts = words.map(countChars); 55 let commonChars = findCommonChars(charCounts); 56 let result = constructResult(commonChars); 57 58 console.log(result); 59 process.exit(); 60});
process.stdin.resume(); process.stdin.setEncoding('utf-8'); let input = ''; process.stdin.on('data', (data) => { input += data; }); process.stdin.on('end', () => { let words = input.trim().split(' '); /** * 统计每个字符串的字符频率 */ function countChars(str) { let charCount = {}; for (let char of str) { charCount[char] = (charCount[char] || 0) + 1; } return charCount; } /** * 找出所有字符串中的公共字符频率(取最小值) */ function findCommonChars(charCounts) { let commonChars = charCounts[0]; for (let i = 1; i < charCounts.length; i++) { let current = charCounts[i]; let tempCommon = {}; for (let char in commonChars) { if (current[char]) { tempCommon[char] = Math.min(commonChars[char], current[char]); } } commonChars = tempCommon; } return commonChars; } /** * 根据字符频率构造结果字符串 */ function constructResult(commonChars) { let result = []; for (let char in commonChars) { result.push(char.repeat(commonChars[char])); } result.sort(); // 按字典序排序 return result.join(''); } // 主逻辑 let charCounts = words.map(countChars); let commonChars = findCommonChars(charCounts); let result = constructResult(commonChars); console.log(result); process.exit(); });

Powered By 可尔物语

浙ICP备11005866号-12