题解 | #统计字符#

统计字符

http://www.nowcoder.com/practice/539054b4c33b4776bc350155f7abd8f5

描述

题目描述

输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数。

本题包含多组输入。

示例

输入:
1qazxsw23 edcvfr45tgbn hy67uj m,ki89ol.\\/;p0-=\\][
输出:
26
3
10
12

知识点:字符串,正则表达式

难度:⭐⭐⭐


题解

方法一:字符匹配

解题思路:

借助ASCII码进行字符匹配

算法流程

  • 四个变量分别代表字母数、空格数、数字数、其他字符数
  • 遍历判断每个字符进行计数
  • 原理是借助ASCII码进行字符匹配

Java 版本代码如下:

import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
        	String str = scanner.nextLine();
        	solution(str);
        }
    }

    private static void solution(String str) {
        // 分别代表字母数、空格数、数字数、其他字符数
        int letterSum = 0;
        int blankSum = 0;
        int numberSum = 0;
        int otherSum = 0;
        // 遍历判断每个字符进行计数
        for(char c : str.toCharArray()) {
            if((c >= 'A' && c <= 'Z') ||  (c >= 'a' && c <= 'z')) {
                letterSum++;
            } else if(c == ' ') {
                blankSum++;
            } else if(c >= '0' && c <= '9') {
                numberSum++;
            } else {
                otherSum++;
            }
        }
        System.out.println(letterSum + "\n" + blankSum + "\n" + numberSum + "\n" + otherSum);
    }
}

复杂度分析

时间复杂度O(N)O(N),需要遍历每个字符

空间复杂度O(1)O(1),只用到四个变量用来计数

方法二:正则表达式

image-20211104201049671

解题思路

利用正则表达式对每个子串进行判断计数

算法流程

  • 四个变量分别代表字母数、空格数、数字数、其他字符数
  • 遍历判断每个字符进行计数
  • 利用正则表达式语法,[A-Za-z]匹配字母,[0-9]匹配数字

Java 版本代码如下:

import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
        	String str = scanner.nextLine();
        	solution(str);
        }
    }

    private static void solution(String str) {
        // 分别代表字母数、空格数、数字数、其他字符数
        int letterSum = 0;
        int blankSum = 0;
        int numberSum = 0;
        int otherSum = 0;
        // 遍历判断每个字符进行计数
        for(char c : str.toCharArray()) {
            String s = String.valueOf(c);
            if(s.matches("[A-Za-z]")) {
                letterSum++;
            } else if(s.equals(" ")) {
                blankSum++;
            } else if(s.matches("[0-9]")) {
                numberSum++;
            } else {
                otherSum++;
            }
        }
        System.out.println(letterSum + "\n" + blankSum + "\n" + numberSum + "\n" + otherSum);
    }
}

复杂度分析

时间复杂度O(N)O(N),需要遍历每个字符

空间复杂度O(1)O(1),只用到四个变量用来计数

华为机试 文章被收录于专栏

华为机试题解

全部评论

相关推荐

投递华为等公司10个岗位
点赞 评论 收藏
转发
投递美团等公司10个岗位
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务