题意整理。

  • 输入一行字符串。
  • 统计出其中英文字母、空格、数字和其它字符的个数。

方法一(循环计数)

1.解题思路

  • 遍历输入字符串中所有字符。
  • 如果是英文字母,letter计数加1;如果是数字,digit计数加1;如果是空格,space计数加1;如果以上都不是,other计数加1。最后将对应的计数变量输出。

动图展示: alt

2.代码实现

#include <iostream>
#include <cstring>
using namespace std;

int main() {

    int letter = 0;
    int digit = 0;
    int space = 0;
    int other = 0;
    
    char buf[1024] = {0};
    cin.getline(buf, sizeof(buf));

    //遍历输入字符串中所有字符
    for(int i=0;buf[i]!='\0';i++){
        //如果是英文字母,letter计数加1
        if((buf[i]>='a'&&buf[i]<='z')||(buf[i]>='A'&&buf[i]<='Z')){
            letter++;
        }
        //如果是数字,digit计数加1
        else if(buf[i]>='0'&&buf[i]<='9'){
            digit++;
        }
        //如果是空格,space计数加1
        else if(buf[i]==' '){
            space++;
        }
        //如果以上都不是,other计数加1
        else{
            other++;
        }
    }
    cout << "letter:" << letter << " digit:" << digit << " space:" << space << " other:" << other << endl;

	return 0;
}

3.复杂度分析

  • 时间复杂度:需要遍历字符串中所有字符,所以时间复杂度为O(n)O(n)O(n)
  • 空间复杂度:需要额外常数级别的空间,所以空间复杂度为O(1)O(1)O(1)