• 寻找“水王”


    一、利用Hashmap和正则表达式中的Pattern和Matcher类统计统计出现的每个ID出现的及次数,并且输出。

    package text530;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Text530 {
        public static void main(String[] args) {
            String words = "002 001 003 002 001 003 001 001 002 001 001 001 001 001 001 001 001 002 004 005 001 001";
            HashMap<String, Integer> map = new HashMap<String, Integer>();
            String reg = "[0-9]+";
            Pattern p = Pattern.compile(reg);
            Matcher m = p.matcher(words);
            Integer count = 0;
            while (m.find()) {
                count++;
                String w = m.group();
                if (null == map.get(w)) {
                    map.put(w, 1);
                } else {
                    int x = map.get(w);
                    map.put(w, x + 1);
                }
            }
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                System.out.println(entry.getKey() + ":" + entry.getValue());
            }
        }
    }

    运行截图:

    二、“水王”是一个论坛中发帖数量超过一半的用户,他的数量大于其他用户所有的数量总和;将所有发帖列表存入一个数组,设置一个标志变量和统计变量,循环这个数组将数组第一个元素赋予标志变量,

    将统计变量置为“1”,若后续元素与之前相同,则统计变量“+1”,若后续元素与之前不相同,则统计变量“-1”,若统计变量变为“0”,则为标志变量置新值,返回最终的结果;

    
    

    package text530;

    
    

    public class Text5301 {
    public static String find(String a[], int n) {
    String X = a[0];
    int num = 0;
    for (int i = 0; i < n; i++) {
    if (num == 0) {
    X = a[i];
    num = 1;
    } else if (a[i] == X) {
    num++;
    } else {
    num--;
    }
    }
    return X;
    }
    public static void main(String[] args) {
    String a[] = { "001", "001", "001", "000", "001", "000", "000", "000", "000", "002", "001", "001", "001", "001", "001", "003", "005" };
    int n = a.length;
    System.out.print("水王ID:");
    System.out.println(find(a, n));
    }
    }

     

    运行截图:

  • 相关阅读:
    亚马逊云储存器S3 BCUKET安全性学习笔记
    (web)Bugs_Bunny_CTF_writeup 部分简单web
    给windows右键添加快捷启动程序
    nmap学习笔记
    暴力美学
    Metasploit学习笔记
    钓鱼+DNS欺骗学习笔记
    第 5 章 if 语句
    第 4 章 操作列表
    3.3 组织列表
  • 原文地址:https://www.cnblogs.com/KYin/p/10950986.html
Copyright © 2020-2023  润新知