Pintia题解——7-15 统计数字字符和空格

7-15 统计数字字符和空格

原题:

本题要求编写程序,输入一行字符,统计其中数字字符、空格和其他字符的个数。建议使用switch语句编写。

输入格式:

输入在一行中给出若干字符,最后一个回车表示输入结束,不算在内。

输出格式:

在一行内按照

blank = 空格个数, digit = 数字字符个数, other = 其他字符个数

的格式输出。请注意,等号的左右各有一个空格,逗号后有一个空格。

.

解题思路:

  1. 引入readline模块并创建接口对象:首先将readline模块引入,并使用createInterface方法创建一个接口对象rl。该对象设置了输入流为标准输入。
  2. 读取输入并存储:通过监听'line'事件,将输入存储在数组buf中。
  3. 统计空格、数字和其他字符的数量:初始化blankdigitother三个变量分别为0。使用for循环遍历字符串text的每个字符,对于每个字符,判断其属于哪一类(空格、数字或其他字符),并将相应的变量+1。
  4. 输出统计结果:使用模板字符串将结果输出,格式为"blank = x, digit = y, other = z",其中x、y、z分别为第3步中统计得到的空格、数字和其他字符的数量

.

JavaScript(node)代码:

const r = require("readline");
const rl = r.createInterface({
    
    
    input: process.stdin
});
let buf = [];
rl.on('line', (input) => buf.push(input));
rl.on('close', () => {
    
    
    const text = buf[0];

    let blank = 0, digit = 0, other = 0;

    for (let i = 0; i < text.length; i++) {
    
    
        const char = text.charAt(i);
        if (/[a-zA-z]/.test(char)) {
    
    
            other++;
        } else if (/[0-9]/.test(char)) {
    
    
            digit++;
        } else if (char === ' ') {
    
    
            blank++;
        } else {
    
    
            other++;
        }
    }

    console.log(`blank = ${
      
      blank}, digit = ${
      
      digit}, other = ${
      
      other}`);

});

.

复杂度分析:

时间复杂度:O(n)
空间复杂度:O(1)

猜你喜欢

转载自blog.csdn.net/Mredust/article/details/133519335